c# - 如何过滤具有日期的列表并仅检索 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。
解决方案
从概念上讲,我认为 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
只会加载符合我们标准的学生(整个对象,而不是投影)。该函数采用指定我们标准的谓词。谓词只是一个函数,它接受我们正在过滤的集合中的记录,并返回一个指示是否应该包含它的函数。
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
记录,但这次它只包含那些在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
反映它现在仅包含DateTime
对象列表的事实。
您仍然可以替换
.OrderBy()
为.OrderByDescending()
更改顺序。
推荐阅读
- ios - 如何使用 iOS 13 在 iPad/iPhone 上隐藏页面缩放栏
- angular - ng zorro 选择不加载选项
- android - 如何从 gmailId -GoogleSignIn 中查找 Gmail 地址
- php - MySQL 在两个具有 Primary ROWS ID 的表中创建新行
- php - 有没有办法将 Laravel 应用程序转换为独立的桌面应用程序?
- google-cloud-platform - 无法在谷歌云平台虚拟机实例上启动 mlflow ui
- javascript - jQuery Animation 淡入淡出……如何创建第二个事件?
- format - 使用 printf() 将浮点数打印为十进制数
- firebase - JS/Android 应用程序可以为谷歌认证的日志用户创建动态 Firebase 数据库吗
- entity-framework-6 - EF6 迁移 - FK 到具有复合键错误的实体