根据给定日期查找列表中的项目

时间:2018-06-04 15:58:12

标签: c# linq

我有以下列表项目以便清楚地显示。我可以想象下面的小列表,可能是数百行。

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    

我要传递ClassNameDate来检索相应的对象。我很难如何在LINQ中实现Date参数。以下实现仅对一个项进行排序和返回。

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个对象。

在其他示例中,如果我提供日期01-01-2018,则应返回12321, 14321个对象。因为01-01-2018早于25325,45329,33325起始日期01-25-2018

1 个答案:

答案 0 :(得分:2)

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>();