Distinct Date with Linq

ぃ、小莉子 提交于 2019-12-23 09:57:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11524853/distinct-date-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!