Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq group month by quarters

Tags:

c#

linq

Is it possible to do a linq group by and group months into quarters, Ie Q1 Jan to apr etc etc

like image 551
Howlingfish Avatar asked Nov 11 '11 03:11

Howlingfish


3 Answers

Something like this

Enumerable.Range(1,12)
    .Select(o => new DateTime(DateTime.Today.Year, o, 1))
    .GroupBy(o => (o.Month - 1) / 3)
like image 176
Ilia G Avatar answered Nov 17 '22 02:11

Ilia G


Here's 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 by is there to simply help the quarters be logically ordered. You can remove the whole clause following the group statement.

With the output of:

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 perhaps translating them to a corresponding enum.

like image 6
Joshua Rodgers Avatar answered Nov 17 '22 03:11

Joshua Rodgers


you can divide an arbitrary list into parts using an overload of the Select method and GroupBy. In your case, assuming 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);
like image 3
saus Avatar answered Nov 17 '22 03:11

saus