Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groupby multiple date properties by month and year in LINQ

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

This is my code:

public class Class1
{
    public Nullable<DateTime> dt1 { get; set; }
    public Nullable<DateTime> dt2 { get; set; }
}

Class1 obj1 = new Class1 { dt1 = new DateTime(2012, 11, 12),
                           dt2 = new DateTime(2012, 12, 12) };
Class1 obj2 = new Class1 { dt1 = new DateTime(2012, 11, 12),
                           dt2 = new DateTime(2012, 12, 12) };
Class1 obj3 = new Class1 { dt1 = null, dt2 = new DateTime(2012, 10, 12) };
Class1 obj4 = new Class1 { dt1 = new DateTime(2012, 10, 12), dt2 = null };
Class1 obj5 = new Class1 { dt1 = null, dt2 = new DateTime(2012, 11, 12) };
Class1 obj6 = new Class1 { dt1 = new DateTime(2013, 10, 12), dt2 = null };

List<Class1> listGoogleTimezone = new List<Class1>
{
    obj1,
    obj2,
    obj3,
    obj4,
    obj5,
    obj6
};

My required result to be like this

MONTH YEAR   COUNT
OCT   2012   2
NOV   2012   3
DEC   2012   2

Help me out

like image 577
Dinesh Avatar asked Dec 22 '16 11:12

Dinesh


2 Answers

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();
like image 79
Ivan Stoev Avatar answered Nov 10 '22 21:11

Ivan Stoev


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.

like image 33
Tamir Vered Avatar answered Nov 10 '22 22:11

Tamir Vered