简体   繁体   English

c#LINQ按作为对象列表的属性的子属性对列表进行排序

[英]c# LINQ sort a list by a subproperty of a property that is a list of objects

I have an Order class, it consists of a number of properties, one of them being Course . 我有一个Order类,它包含许多属性,其中一个是Course The Course object contains a list of MeetingDays . Course对象包含MeetingDays的列表。 Each MeetingDay object contains numerous properties, one of which is StartDate . 每个MeetingDay对象包含许多属性,其中之一是StartDate

Now I want to sort ( OrderBy ) a list of orders, ordering it by the StartDate property of a MeetingDay . 现在,我想排序( OrderBy )订单列表,通过MeetingDayStartDate属性对其进行MeetingDay

Since an order can have several MeetingDays : I also have a date, and I only want to sort by the MeetingDay per order that is equal to the date parameter. 由于一个订单可以具有多个MeetingDays :我也有一个日期,并且我只想按与date参数相等的每个订单按MeetingDay进行排序。

So if one order starts at 10 am and ends at 2 pm I want it ordered in my list before another order that starts at 3 pm and ends at 6 pm. 因此,如果一个订单从上午10点开始到下午2点结束,我希望它在我的列表中先于另一个订单从下午3点开始到下午6点结束。

Edit 编辑

It would be nice if something like this was possible: 如果可能的话,这将是很好:

var sortedOrders = orders.OrderBy(x => x.Course.MeetingDays.StartDate.Date == date.Date).ToList();

仅在一个MeetingDay.StartDate匹配日期正好一个日期时有效:

var sortedOrders = orders.OrderBy(x => x.Course.MeetingDays.Single(y => y.StartDate.Date == date.Date).StartDate).ToList();

Since (according to the comments) you are guaranteed, that each order contains a MeetingDay that matches your given day, the following expression will accomplish what you want: 由于可以保证(根据评论)每个order包含与给定日期匹配的MeetingDay ,因此以下表达式将完成您想要的事情:

var sortedOrders = myOrders
    .OrderBy(order => order
        .Course
        .MeetingDays
        .Single(day => day.StartDate.Date == date.Date)
        .StartDate)
    .ToList();

Should, unexpectedly, there be zero or more than one matching MeetingDay , an exception will be thrown at the call to Single . 出乎意料的是,如果存在零个或多个匹配的MeetingDay ,则对Single的调用将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM