在列表中找到相应的项目 [英] Find the corresponding item in the List

查看:79
本文介绍了在列表中找到相应的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表项以便清楚显示,我可以形象地看到后面的小列表,该列表可能是几百行.

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  
32342       Physics      08-25-2017  
34345       Chemistry    08-25-2017 
25325       Math         01-25-2018     
44345       Chemistry    01-25-2018    

我要传递ClassNameDate来检索相应的对象.我很难在LINQ中实现Date参数

I have ClassName and Date to pass to retrieve the corresponding object. I am having difficulty how to implement Date parameter into the LINQ

public Course GetClassesByNameAndDate(string className, DateTime date, List<Courses> allCourses)
{
    Course course  = allCourses.Where( x=> x.ClassName == className & x.StartDate <= date );

}

例如,我实现的逻辑返回了两个类.但是,我只需要开始日期更接近给定日期的项目即可.

For example, the logic that I implement returns me two classes. However, I only need to have the item which startdate is closer to the given date.

如果我通过today date并且课程名称也通过Math,那么它应该从列表中返回我25325 courseID对象.

If I pass today date and also course name as Math, then it should return me 25325 courseID object from the list.

尽管有两门数学课程,但是已经开始01-25-2018的一门课程是给定日期的最新课程.

Even though there are two math courses, but the one which has started 01-25-2018 is the latest course to the given date.

在另一个示例中,如果我给出一个日期01-01-2018,则它应该返回12321该对象.因为01-01-2018早于25325开始日期(01-25-2018).

In other example, if I give a date 01-01-2018, then it should return 12321 that object. Because 01-01-2018 is earlier than the 25325 startdate which is 01-25-2018.

推荐答案

您可以 OrderByDescending() ,它的排序很稳定,因此您可以使用

You can OrderBy() or OrderByDescending(), it's stable sorting so then you can select the first one using FirstOrDefault() or just First()

allCourses.Where( x=> x.ClassName == className && x.StartDate <= date ).OrderByDescending(x=> x.StartDate ).FirstOrDefault();

这篇关于在列表中找到相应的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆