After some hours of trying and researching I'm still stuck with the following problem.
I have a list of customers, each customer has a list of orders. I now want to sort the list of customers by their highest order number. Another aspect is that not every customer has an order, so for sorting i want to replace the missing order number with an “-“ sign.
My first approach won’t work because it can’t compare the object, but it explains the problem quite well.
customers.OrderBy(m => m.Orders == null ? "-" : m.Orders.LastOrDefault().OrderNumber.ToString());
After reading the link below I ended up with this code, but that is not working either.
how do I sort a collection with child property?
customers.OrderBy(c => c.Orders.OrderBy(o => o == null ? "-" : o.OrderNumber.ToString()).Select(o => o == null ? "-" : o.OrderNumber.ToString()).ToList();
Can someone tell me how I can do this best?
Best Regards
Edit:
Here are the entities (not full entity) I'm trying to sort. I'm working with entity framework and I've already read out the customers as an IQueryable and now I need to sort this.
Customer
public class Customer
{
public int ID { get; set; }
public virtual List<Order> Orders { get; set; }
}
Order
public class Order {
public int ID { get; set; }
public int OrderNumber { get; set; }
public virtual Customer Customer { get; set; }
}
Now the customer does not necessarily have a list of orders associated. Meaning a customer can have 0,1 or n orders assigned to him, that's what I meant with null.