Linq group month by quarters

后端 未结 4 1442
一个人的身影
一个人的身影 2020-12-30 12:21

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

相关标签:
4条回答
  • 2020-12-30 12:48

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

    0 讨论(0)
  • 2020-12-30 12:49

    Something like this

    Enumerable.Range(1,12)
        .Select(o => new DateTime(DateTime.Today.Year, o, 1))
        .GroupBy(o => (o.Month - 1) / 3)
    
    0 讨论(0)
  • 2020-12-30 13:02

    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.

    0 讨论(0)
  • 2020-12-30 13:07

    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);
    
    0 讨论(0)
提交回复
热议问题