根据给定日期从列表中查找项目 [英] Find items from the list based on given date
问题描述
为了清楚显示,我有以下列表项.我可以形象地看到下面的小列表,该列表可能是几百行.
I have the following List item in order to display clearly. I could visualize the small list follows, that could be hundreds rows.
CourseId ClassName StartDate
-------- -------- --------
12321 Math 08-25-2017
14321 Math 08-25-2017
32342 Physics 08-25-2017
34345 Chemistry 08-25-2017
25325 Math 01-25-2018
45329 Math 01-25-2018
33325 Math 01-25-2018
44345 Chemistry 01-25-2018
我要传递ClassName
和Date
来检索相应的对象.我很难在LINQ中实现Date
参数.以下实现仅排序并返回一项.
I have ClassName
and Date
to pass to retrieve the corresponding objects. I am having difficulty how to implement Date
parameter into the LINQ. The following implementation sorts and returns only one item.
public List<Course> GetClassesByNameAndDate(string className, DateTime date, List<Courses> allCourses)
{
List<Course> courses = allCourses.Where( x=> x.ClassName == className && x.StartDate <= date ).OrderByDescending(x=> x.StartDate ).ToList();
}
如果我通过today date
并且课程名称也通过Math
,那么它应该从列表中返回25325,45329,33325 courseIDs
对象.
If I pass today date
and also course name as Math
, then it should return me 25325,45329,33325 courseIDs
objects from the list.
在另一个示例中,如果我给定日期01-01-2018
,则它应该返回12321, 14321
对象.因为01-01-2018
早于25325,45329,33325
开始日期,即01-25-2018
.
In other example, if I give a date 01-01-2018
, then it should return 12321, 14321
objects. Because 01-01-2018
is earlier than the 25325,45329,33325
startdate which is 01-25-2018
.
推荐答案
我想我终于了解了要求.您不只想要一项.您也不希望列表包含startDate
为<= date
的所有项目.但是,您希望整个项目组的起始日期最接近(如果所有项目都具有相同的startDate
).您可以GroupBy
日期:
I guess finally i have understood the requirement. You don't want only one item. You also don't want the list with all items where the startDate
is <= date
. But you want the whole group of items with the closest start-date(if all of them have the same startDate
). You can GroupBy
the date:
List<Course> courses = allCourses
.Where( x=> x.ClassName == className && x.StartDate <= date )
.OrderByDescending(x=> x.StartDate)
.GroupBy(x => x.StartDate)
.FirstOrDefault()?.ToList() ?? new List<Course>();
这篇关于根据给定日期从列表中查找项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!