Reputation: 868
I have a List of objects that I need to sort based on two columns:
List<Customers> customers = CustomerService.GetAll();
Now, the existing code is as follows:
customers.Sort(new CustomerComparer(sortColumn));
where Sort Column could be Date, Name, Amount, Description.
In the comparer class I have:
public class CustomerComparer : IComparer<Customer>
{
public CustomerComparer(string expression){}
public int Compare(Customer c, Customer d)
{
int value = 0;
switch(expression)
{
case "Name":
value = String.Compare(c.Name, d.Name,StringComparison.InvariantCultureIgnoreCase);
break;
case "Date":
value = DateTime.Compare(b.Date, d.Date);
break;
case "Description":
value = String.Compare(c.Name, d.Name,StringComparison.InvariantCultureIgnoreCase);
break;
}
return value;
}
}
Given this scenario, how can I sort based on two Columns? for instance I should always be able to sort on any of those columns, but then BY Date always like:
DESCRIPTION ,DATE
NAME, DATE
etc..
Upvotes: 0
Views: 88
Reputation: 120440
How about ditching the CustomComparer and using Linq? It then becomes trivial to order by multiple columns.
var orderedList =
customers.OrderBy(c => c.Name).ThenByDescending(c => c.Date).ToList();
Upvotes: 2