【问题标题】:Distinct Date with Linq与 Linq 不同的日期
【发布时间】:2012-07-17 14:34:34
【问题描述】:

我有一个名为 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 to Entities 不支持指定的类型成员“日期”。 只有初始化器、实体成员和实体导航属性 支持。

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

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

任何帮助将不胜感激。

【问题讨论】:

标签: c# linq datetime linq-to-entities distinct


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多