Linq quarterly group

Is it possible to make a linq group by groups and months of the group in quarters, i.e. Q1 Jan to apr, etc. etc.

+6
source share
4 answers

Something like that

Enumerable.Range(1,12) .Select(o => new DateTime(DateTime.Today.Year, o, 1)) .GroupBy(o => (o.Month - 1) / 3) 
+12
source

Here is a basic example demonstrating this:

 var dates = new[] { new DateTime(2011, 12, 25), new DateTime(2011, 11, 25), new DateTime(2011, 5, 4), new DateTime(2011, 1, 3), new DateTime(2011, 8, 9), new DateTime(2011, 2, 14), new DateTime(2011, 7, 4), new DateTime(2011, 11, 11) }; var groupedByQuarter = from date in dates group date by (date.Month - 1)/3 into groupedDates orderby groupedDates.Key select groupedDates; foreach(var quarter in groupedByQuarter) { Console.WriteLine("Q: {0}, Dates: {1}", quarter.Key, string.Join(", ", quarter)); } 

The order is simply to help the neighborhoods be logically ordered. You can delete the offer of the target according to the group operator.

With an exit:

 Q: 0, Dates: 1/3/2011 12:00:00 AM, 2/14/2011 12:00:00 AM Q: 1, Dates: 5/4/2011 12:00:00 AM Q: 2, Dates: 8/9/2011 12:00:00 AM, 7/4/2011 12:00:00 AM Q: 3, Dates: 12/25/2011 12:00:00 AM, 11/25/2011 12:00:00 AM, 11/11/2011 12:00:00 AM 

Obviously, you will need to correct the quarter numbers by adding one or, possibly, translating them into the corresponding enumeration.

+5
source

you can split an arbitrary list into parts using the overload of the Select and GroupBy methods. In your case, if the months in the list are in the correct order, the following should work:

 var groups = yourList .Select((item, index) => new { item, index }) .GroupBy(indexedItem=>indexedItem.index/3); 
+3
source

Yes, this can be achieved using the LINQ to SQL GroupBy function, if you define qouters somewhere in your database or you can write code that will handle this action, it all depends on what data is available for this assessment.

-1
source

Source: https://habr.com/ru/post/901267/


All Articles