c#Linq选择不同的日期时间天

时间:2013-09-18 15:01:33

标签: c# .net visual-studio-2010 linq

我有以下方法,我计划返回一堆不同的日期时间对象。通过不同我意味着独特的日子(不包括时间)。

问题是,DateTime对象有不同的时间,因此即使它们是同一天,也会评估为唯一。

如何让查询忽略日期的时间部分,只是为了评估唯一性的日期?

    public List<DateTime> DistinctNoticeDates()
    {
        return (from notices in this.GetTable<Notice>()
                orderby notices.Notice_DatePlanned descending
                select notices.Notice_DatePlanned).Distinct().ToList();
    }

感谢。

5 个答案:

答案 0 :(得分:4)

尝试使用Date属性来获取DateTime结构的日期:

public List<DateTime> DistinctNoticeDates()
{
    return (from notices in this.GetTable<Notice>()
            orderby notices.Notice_DatePlanned descending
            select notices.Notice_DatePlanned.Date)
            .Distinct()
            .ToList();
}

答案 1 :(得分:1)

public List<DateTime> DistinctNoticeDates()
{
    return (from notices in this.GetTable<Notice>()
            orderby notices.Notice_DatePlanned descending
            select notices.Notice_DatePlanned.Date).Distinct().ToList();
}

答案 2 :(得分:1)

您可以使用Date属性删除DateTime的时间部分:

public List<DateTime> DistinctNoticeDates()
{
    return 
        (from notices in this.GetTable<Notice>()
         orderby notices.Notice_DatePlanned descending
         select notices.Notice_DatePlanned.Date)
        .Distinct()
        .ToList();
}

答案 3 :(得分:1)

将您的查询更改为“将日期时间”“转换”为其日期部分

public List<DateTime> DistinctNoticeDates()
    {
        return (from notices in this.GetTable<Notice>()
                orderby notices.Notice_DatePlanned descending
                select notices.Notice_DatePlanned.Date).Distinct().ToList();
    }

此外,如果您只想按日期部分订购,我会在不同之后订购。这样您就可以订购较小的列表,从而提高性能

public List<DateTime> DistinctNoticeDates()
    {
        return (from notices in this.GetTable<Notice>()                    
                select notices.Notice_DatePlanned.Date).Distinct().OrderByDescending().ToList();
    }

答案 4 :(得分:-1)

尝试实现DateTime比较器,它将仅按天比较日期(如果天数相等则返回true)并将其用作linq Distinct方法的参数。例如:

class DateTimeByDayComparer : IEqualityComparer<DateTime>
{
       public bool Equals(DateTime x, DateTime y)
       {
           return x.Day == y.Day;
       }
}

public List<DateTime> DistinctNoticeDates()
{
     var comparer = new DateTimeByDayComparer();
     return this.GetTable<Notice>().OrderByDescending(n => n.Notice_DatePlanned).Distinct(comparer).ToList();
}