根据给定的日期从列表中查找项目[英] Find items from the list based on given date

问题描述

```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
```

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

}
```

推荐答案

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

问题描述

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
```

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

}
```

If I pass today date and also course name as Math, then it should return me 25325,45329,33325 courseIDs objects from the list.

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.

推荐答案

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