与Linq不同的日子 [英] Distinct Date with Linq

查看:114
本文介绍了与Linq不同的日子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Billings的实体,其属性为DateTime。我需要独特地找到日期,以便我可以通过他们做一些事情。
我试过:

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

foreach(var day in DistinctYearMonthsDays)

但我得到 foreach ):


LINQ不支持指定的类型成员'Date'到实体。
只支持初始化器,实体成员和实体导航属性


搜索后我也尝试过以下没有成功:

  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));

任何帮助将非常感谢。

解决方案

您可以使用内置的EntityFunctions。您的查询将成为:

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

有关EntityFunction的更多信息,请查看 MSDN


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.

解决方案

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.

这篇关于与Linq不同的日子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆