Is it possible to do a linq group by and group months into quarters, Ie Q1 Jan to apr etc etc
Something like this
Enumerable.Range(1,12)
.Select(o => new DateTime(DateTime.Today.Year, o, 1))
.GroupBy(o => (o.Month - 1) / 3)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With