c# - 如何筛选具有日期的列表并仅检索 7 天内的数据

标签 c# asp.net linq lambda

所以我有这个模型:

Student Model

public int StudentId {get; set;}
public string StudentName {get; set;}
public DateTime EnrollDate {get; set;}

我还有一个学生模型列表,类似于

List<Student> listOfStudents = new List<Student>();

在该列表中有 100 名学生的详细信息和注册日期。

我接下来要做的是对列表进行排序,从最新的到最旧的显示。

listOfStudents.Sort((x, y) => DateTime.Compare(y.EnrollDate, x.EnrollDate));

它正在运行。但是,我目前正在努力只显示从今天起 7 天内的 EnrollDate。

最佳答案

从概念上讲,我认为 LINQ 很像 SQL。您有 SELECT 部分,这是您的投影(即我要从这组数据中提取什么?)。如果您从 LINQ 中省略 Select() 子句,您将获得整个记录,而如果您只想摘取其中的一部分,则只能获得一部分。您有 WHERE 部分,它是一个限制器或过滤条件,当应用于集合时,只会拉回满足所述条件的记录。最后,您可以应用一些操作来影响返回集合的顺序。这就是 OrderBy()OrderByDescending() 发挥作用的地方。因此,让我们将这些概念映射到下面的示例中


没有 Select(),但我们有 Where()OrderBy()

var then = DateTime.Now.AddDays(-7); //One portion of our Where. More below
var sortedStudents = listOfStudents
  //Our predicate. 's' = the Student passed to the function. Give me only the students
  //where s.EnrollDate is greater or equal to the variable 'then' (defined above)
  .Where(s => s.EnrollDate >= then) 
  //We have no Select statement, so return whole students
  //And order them by their enrollment date in ascending order
  .OrderBy(s => s.EnrollDate);

运行时,sortedStudents加载符合我们的学生(整个Student 对象,而不是投影) Where() 条件。 Where() 函数采用指定条件的谓词。谓词只是一个函数,它从我们正在过滤的集合中接受一条记录,并返回一个 bool 指示它是否应该被包括在内。


让我们通过调整 Where()

来改变过滤器
//Notice we've changed 'then' from 7 days ago to a fixed point in time: 26 June 2018
var then = new DateTime.Parse("26 June 2018"); 
var sortedStudents = listOfStudents
  .Where(s => s.EnrollDate >= then) 
  //Still no Select(). We'll do that next
  .OrderBy(s => s.EnrollDate);

就像之前一样,sortedStudents 将拥有完整的Student 记录,但这次它只会包含那些在之后/em> 2018 年 6 月 26 日,由我们的谓词指定。


让我们添加一个Select()

var then = new DateTime.Parse("26 June 2018"); 
var dates = listOfStudents
  .Where(s => s.EnrollDate >= then) 
  .Select(s => s.EnrollDate);

现在我们对其进行了更改,而不是拉回 整个 Student,我们只提取 EnrollDate。请注意,我已将接收变量的名称从 sortedStudents 更改为 dates,以反射(reflect)它现在仅包含 DateTime 对象列表这一事实。


您仍然可以将 .OrderBy() 替换为 .OrderByDescending() 以更改顺序。

关于c# - 如何筛选具有日期的列表并仅检索 7 天内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50993035/

相关文章:

c# - 在遍历 Xdocument 时获取 xDocument 元素的子节点

c# - 如何从 linq 或 IQueryable 对象获取可执行的 sql 语句?

c# - 应用程序退出时显示等待消息

c# - 自动批量发送短信并通过网络界面

asp.net - SignalR 2.0 超时连接

c# - 无法评估表达式,因为代码已优化或 native 框架位于调用堆栈顶部

linq - 如何创建一个必须满足两个值的谓词,其中一个是值列表?

c# - 用C#学习单一职责原则

c# - 如何使用 JSON.Net 将 JsonExtensionData (Dictionary<string, JToken>) 应用于另一个对象

c# - 从多级列表中的任何位置删除对象(绕过图算法搜索)