Groupby multiple date properties by month and year in LINQ

后端 未结 2 925
南方客
南方客 2021-01-05 11:42

I need to group by multiple properties by month and year in C# LINQ

This is my code:

public class Class1
{
    public Nulla         


        
相关标签:
2条回答
  • 2021-01-05 12:13

    You need to collect all the dates using SelectMany (in this particular case filter out the null values) and then do the typical GroupBy / Count projection:

    var result = listGoogleTimezone
        .SelectMany(x => new[] { x.dt1, x.dt2 }.Where(dt => dt != null).Select(dt => dt.Value))
        .GroupBy(dt => new { dt.Month, dt.Year })
        .OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month) // optional
        .Select(g => new
        {
            g.Key.Month,
            g.Key.Year,
            Count = g.Count()
        }).ToList();
    
    0 讨论(0)
  • 2021-01-05 12:14

    If you have MoreLinq referenced you can use make Ivan's answer cleaner by using CountBy:

    var result = listGoogleTimezone
        .SelectMany(x => new[] { x.dt1, x.dt2 }
            .Where(dt => dt != null)
            .Select(dt => dt.Value))
        .CountBy(x => new { Year = x.Year, Month = x.Month });
    

    This will can you an IEnumerable<KeyValuePair<TKey, int>> where the TKey is an anonymous type with Year and Month and the int is the count.

    0 讨论(0)
提交回复
热议问题