首页 > 解决方案 > 如何过滤具有日期的列表并仅检索 7 天内的数据

问题描述

所以我有这个模型:

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。

标签: c#asp.netlinqlambda

解决方案


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


Select(),但我们确实有 aWhere()和 anOrderBy()

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只会加载符合我们标准学生(整个对象,而不是投影)。该函数采用指定我们标准的谓词。谓词只是一个函数,它接受我们正在过滤的集合中的记录,并返回一个指示是否应该包含它的函数。 StudentWhere()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记录,但这次它只包含那些在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. 请注意,我已将接收变量的名称从 更改sortedStudentsdates反映它现在仅包含DateTime对象列表的事实。


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


推荐阅读