c#Linq选择不同的日期时间天
我有以下方法,我计划返回一堆不同的日期时间对象。 通过不同我意味着独特的日子(不包括时间)。
问题是,DateTime对象具有不同的时间,因此即使它们是同一天,也会评估为唯一。
如何让查询忽略日期的时间部分,只是为了评估唯一性的日期?
public List DistinctNoticeDates() { return (from notices in this.GetTable() orderby notices.Notice_DatePlanned descending select notices.Notice_DatePlanned).Distinct().ToList(); }
谢谢。
尝试使用Date
属性来获取DateTime
结构的日期:
public List DistinctNoticeDates() { return (from notices in this.GetTable() orderby notices.Notice_DatePlanned descending select notices.Notice_DatePlanned.Date) .Distinct() .ToList(); }
public List DistinctNoticeDates() { return (from notices in this.GetTable() orderby notices.Notice_DatePlanned descending select notices.Notice_DatePlanned.Date).Distinct().ToList(); }
您可以使用Date
属性DateTime
的时间部分:
public List DistinctNoticeDates() { return (from notices in this.GetTable() orderby notices.Notice_DatePlanned descending select notices.Notice_DatePlanned.Date) .Distinct() .ToList(); }
更改查询以将dateTime“强制转换”为其日期部分
public List DistinctNoticeDates() { return (from notices in this.GetTable() orderby notices.Notice_DatePlanned descending select notices.Notice_DatePlanned.Date).Distinct().ToList(); }
此外,如果您只想按日期部分订购它们,我会在不同之后订购它们。 这样您就可以订购较小的列表,从而提高性能
public List DistinctNoticeDates() { return (from notices in this.GetTable() select notices.Notice_DatePlanned.Date).Distinct().OrderByDescending().ToList(); }
尝试实现DateTime
比较器,它将按天比较日期(如果天数相等则返回true)并将其用作linq Distinct
方法的参数。 例如:
class DateTimeByDayComparer : IEqualityComparer { public bool Equals(DateTime x, DateTime y) { return x.Day == y.Day; } } public List DistinctNoticeDates() { var comparer = new DateTimeByDayComparer(); return this.GetTable().OrderByDescending(n => n.Notice_DatePlanned).Distinct(comparer).ToList(); }