Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct Date with Linq

I have an entity called Billings with a property of DateTime. I need to uniquely find the dates so I can go through them and do some stuff. I tried:

var DistinctYearMonthsDays = (from t in db.Billings 
                              where t.DateTime.HasValue 
                              select   t.DateTime.Value.Date).Distinct();

foreach (var day in DistinctYearMonthsDays)

but I get (on the foreach):

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

After searching I also tried the following without success:

IEnumerable<DateTime> DistinctYearMonthsDays = db.Billings
    .Select(p => new 
        {              
            p.DateTime.Value.Date.Year,
            p.DateTime.Value.Date.Month,
            p.DateTime.Value.Date.Day 
         }).Distinct()
         .ToList()
         .Select(x => new DateTime(x.Year,x.Month,x.Day));

Any help will be very much appreciated.

like image 657
user1531996 Avatar asked Jul 17 '12 14:07

user1531996


1 Answers

You can use the built in EntityFunctions. Your query would become:

var DistinctYearMonthsDays = (from t in db.Billings 
                              where t.DateTime.HasValue 
                              select EntityFunctions.TruncateTime(t.DateTime)).Distinct();

For more about EntityFunctions, check MSDN.

like image 67
Jeff Siver Avatar answered Oct 05 '22 22:10

Jeff Siver