c# Linq 选择不同的日期时间日期
本文关键字:日期 时间 Linq 选择 | 更新日期: 2023-09-27 18:32:01
我有以下方法,我计划返回一堆不同的日期时间对象。"不同"是指独特的日子(不包括时间)。
问题是,DateTime 对象具有不同的时间,因此即使它们是同一天,也会评估为唯一时间。
如何让查询忽略日期的时间部分,而只评估日期的唯一性?
public List<DateTime> DistinctNoticeDates()
{
return (from notices in this.GetTable<Notice>()
orderby notices.Notice_DatePlanned descending
select notices.Notice_DatePlanned).Distinct().ToList();
}
谢谢。
尝试使用 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();
}
public List<DateTime> DistinctNoticeDates()
{
return (from notices in this.GetTable<Notice>()
orderby notices.Notice_DatePlanned descending
select notices.Notice_DatePlanned.Date).Distinct().ToList();
}
您可以使用
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();
}
将查询更改为将日期时间"强制转换"到其日期部分
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();
}
尝试实现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();
}