开发者

Sorting Lists with sub items in C#

开发者 https://www.devze.com 2023-01-15 06:08 出处:网络
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.

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 h开发者_运维知识库as a nice clean way.


Try something like this:

List<MyOrder> sortedList = myOrders
    .OrderBy(myOrder => myOrder.OrderItems.Min(myItem => myItem.ItemCreateDate))
    .ToList();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消