WulfgarDK
WulfgarDK

Reputation: 155

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. The Course object contains a list of MeetingDays. Each MeetingDay object contains numerous properties, one of which is StartDate.

Now I want to sort (OrderBy) a list of orders, ordering it by the StartDate property of a 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.

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.

Edit

It would be nice if something like this was possible:

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

Upvotes: 2

Views: 2522

Answers (2)

olydis
olydis

Reputation: 3310

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:

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.

Upvotes: 2

Tim Pohlmann
Tim Pohlmann

Reputation: 4430

This will only work if exactly one MeetingDay.StartDate match date:

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

Upvotes: 0

Related Questions