Bob Tway
Bob Tway

Reputation: 9603

Linq - flatten and sort by parent

Simple question, not sure what the best answer is although I suspect it involves Linq.

I have a list of "order" objects, each of which has an Id and a collection of "orderItem" objects, each of which in turn has an Id. However, the orderItem objects don't contain a direct reference to the "order" ID.

I need to get a list of all the "orderItem" objects of all the "orders" in the list, sorted first by orderItemID and then orderID.

(If I had a reference to orderID in orderItemID it would be very easy but I don't, and it'd be ugly and inefficient to add one just to do this).

I can easily get the list of all the orderItem objects by iteration, obviously, but then I can't do the sorting I need. Thoughts?

Upvotes: 1

Views: 253

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

That's nice and easy:

var query = from order in orders
            from item in order.OrderItems
            orderby item.OrderItemId, order.OrderId
            select item;

Upvotes: 5

Related Questions