1

I have a list which elements follows a sequence. I want use aggregate with OrderBy and ThenBy

List<string> list = new List<string> {"codCustomer", "customerName", "address1", "address2"};

list = list
    .OrderBy(o => o.codCustomer)
    .ThenBy(o => o.customerName)
    .ThenBy(o => o.address1)
    .ThenBy(o => o.addres2)

This list contain many elements and I want use aggregate with OrderBy and ThenBy, but I don't know how do it.

The matter is that this list is passed as a parameter and contains the fields to sort.

beto13
  • 49
  • 6
  • Is one `list` a list of property names and another `list` a different list of objects that have those properties? – Jon Hanna Jun 26 '15 at 01:16

1 Answers1

0

You should define a class called Customer with the properties Code, Name, Address1 and Address2 and create a list of customer objects, not a list of strings. Then you can order the list of customers the way you described.

class Customer 
{
   public string Code { get; set; }
   public string Name { get; set; }
   public string Address1 { get; set; }
   public string Address2 { get; set; }
}
...
// at some point
List<Customer> customers = new List<Customer>();
customers.Add(new Customer()
{
   Code = "cod1",
   Name = "nam1",
   Address1 = "ad1",
   Address2 = "ad2"
};
// ... more customers
// you order customers the way you need
List<Customer> orderedCustomers = customers.OrderBy(p => p.Code).ThenBy(p => p.Name).ToList(); // you can continue ordering by all the properties if you want.
Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74
  • 1
    The matter is that this list is passed as a parameter and contains the fields to sort. – beto13 Jun 25 '15 at 22:02
  • 1
    EF has deferred execution so you can use IF statements and order by any property. Something like: if (sortByCode) var result = customers.OrderBy(p => p.Code); The simplest solution I can think of, even though it's not the best, is to pick each property name from the list and order by that property and then continue with the next property (you are iterating over the list of properties to order by). Read this question: http://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on-an-iqueryable-using-a-string-column-name-within-a-gene – Francisco Goldenstein Jun 25 '15 at 22:21