Reputation: 4737
I'm trying to sort a list of orders and items based on a the earliest (lowest) creation date of one of the items in the list.
So I have:
public MyOrder
{
orderid int;
IList<MyItems> orderitems;
}
public MyItems
{
DateTime itemcreatedate;
}
Say Order1 has two items in it with itemcreatedate 6/1/2010 and 6/15/2010
Order2 has two items in it with itemcreatedate 4/1/2010 and 6/10/2010
I'd like my sorted list to then be Order2, Order1
My meager unfrozen caveman developer brain can see a brute force iterative way to make it happen, but I'm wondering if anyone has a nice clean way.
Upvotes: 4
Views: 702
Reputation: 9698
Here is my (untested!) code :
List<MyOrder> orders = GetSomeOrders();
var orderCreateDateMap = orders.ToLookup(order => order.orderitems.Min(o2 => o2.itemcreatedate));
var sortedGroups = orderCreateDateMap.OrderBy(g => g.Key);
var sortedOrders = sortedGroups.SelectMany(g => g);
The concept is somewhat similar to Mark's one, but I use lookup to avoid IEnumerable<>.Min
method to be called multiple times.
Upvotes: 0
Reputation: 838156
Try something like this:
List<MyOrder> sortedList = myOrders
.OrderBy(myOrder => myOrder.OrderItems.Min(myItem => myItem.ItemCreateDate))
.ToList();
Upvotes: 6