简体   繁体   English

C#列表 <Items> 与DateTime获取过去6周的全部

[英]c# List<Items> with DateTime get all from last 6 weeks

I have a List and Item contains a DateTime property. 我有一个List,并且Item包含DateTime属性。 The list is populated with a lot of data. 该列表中填充了很多数据。

I need to get the last 6 weeks items from today. 我需要从今天开始获取最近6周的物品。

I'm thinking to do it like this: 我正在考虑这样做:

6 weeks = 6 weeks x 7 days = 42 days 6周= 6周x 7天= 42天

DateTime today = DateTime.Now;

DateTime startDate = today.AddDays(42);

List<Item> list = list.Where(t=>t.Created.Date >= startDate.Date && t.Created.date <= today.Date)

Is there a better way to achieve the same? 有没有更好的方法可以达到相同目的?

You can use a TimeSpan and DateTime.Subtract to achieve the same thing in an (arguably) more idiomatic form. 您可以使用TimeSpanDateTime.Subtract以(可能是)更惯用的形式实现同一件事。

var sixWeeks = TimeSpan.FromDays(42);
var list = source.Where(t=>t.Created.Date >= DateTime.Now.Date.Subtract(sixWeeks));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM