I need to group by multiple properties by month and year in C#
LINQ
This is my code:
public class Class1
{
public Nulla
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();
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.