所以我有这个模型:
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/