Saad Khattak
Saad Khattak

Reputation: 68

Sorting a list based on a condition placed on property of its inner list

I have a List<Order> and each Order has an inner list List<Item>, each Item has a property IsLateForDelivery. I want to sort the list of orders so that an Order with most number of Items that are Late for delivery is at index 0.

Upvotes: 0

Views: 312

Answers (2)

Marco Salerno
Marco Salerno

Reputation: 5203

This is how to do it:

class Program
{
    static void Main(string[] args)
    {
        List<Order> orders = new List<Order>();
        //List seed
        orders = orders.OrderByDescending(x => x.Items.Count(y => y.IsLateForDelivery)).ToList();
    }
}

public class Order
{
    public List<Item> Items { get; set; }
}

public class Item
{
    public bool IsLateForDelivery { get; set; }
}

Upvotes: 0

jalsh
jalsh

Reputation: 823

Using System.Linq;
//List<Order> Orders
Orders.OrderByDescending(order => order.Items.Count(item => item.IsLateForDelivery))

Upvotes: 1

Related Questions