LINQ DateTimeOffset与今天日期的比较

3

我有一个带有DateTimeOffset属性的类:

public class Sample 
{
    public DateTimeOffset expires { get; set; }
}

最终会形成它们的集合:
IEnumerable<Sample> collection;

2个问题:

  1. 创建一个方法,返回集合中所有在当前时间之后且仍然是今天(即午夜之前)过期的样品项的最佳方法是什么?

  2. 返回集合中所有在接下来的24小时内到期的样品项的最佳方法是什么?

3个回答

4
// greater than now, still today            
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.Date == DateTime.Today);

// expires in the next 24 hours
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.DateTime < DateTime.Now.AddHours(24));

谢谢您的回答,但是根据问题所述,当d.expires是DateTimeOffset时,这种方法不起作用。 - Chris
好的,请再试一次,我已经调整了查询以偏移类型。很抱歉我错过了那个。 - danijels

0
var list1 = 
    collection.Where
        (c => c.expires.DateTime > DateTime.Now && 
              c.expires.DateTime < DateTime.Today.AddDays(1));

var list2 = 
    collection.Where
        (c => c.expires.DateTime >= DateTime.Now && 
              c.expires.DateTime <= DateTime.Now.AddHours(24));

谢谢您的回答,但是根据问题所述,当c.expires为DateTimeOffset时,这种方法不起作用。 - Chris

-1

将计算出的值进行“缓存”以提高性能是一个好的实践,否则它将在每个循环中重新计算(就像循环内部一样):

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime now = DateTime.Now;
DateTime next24hrs = now.AddHours(24);
IEnumerable<Sample> next24HoursSamples = collection.Where(sample=>sample.expires>now && sample.expires<next24hrs).ToList();
IEnumerable<Sample> sameDaySamples = next24HoursSamples.Where(sample=>sample.expires>=now && sample.expires<tomorrow).ToList();

请注意,sameDay列表是从已过滤的列表中检索出来的(same day是下一个24小时的子集),因此要过滤的项目较少。
编辑:我更新了代码以使用立即查询执行模型,因为@danijels警告了延迟执行。

我认为这不是很明智的做法。由于Linq延迟执行,计算DateTime值并将它们传递给Linq意味着理论上,在实际执行时,这些值可能已经发生了变化。只需要考虑在午夜前几秒钟运行此代码以及在允许新的一天开始之间进行某些操作,那么一切都会出错。更不用说如果这是要编译成Linq查询的话。 - danijels
这在理论上可能是正确的,但实际上延迟执行也可能会持续到午夜并搞砸一切。这只是一个好的实践,而不是规则。 - jaraics

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接