Nowadays LINQ and Lambda expressions are very popular among .Net developers for query data. To control the sort order we use “OrderBy” clause and most of the times we need to use more than one field to use for sorting.
Here is my data collection.
List customers = new List() {
new Customer("ADAMS", "DEANIE"),
new Customer("AARON", "ELVIA"),
new Customer("ADAMS", "DAVID"),
new Customer("AARON", "KIMBERLEI"),
new Customer("ADAMS", "DENIS"),
new Customer("ALLEN", "SAGE"),
new Customer("CHRIS", "ANDERSEN"),
new Customer("ADAMS", "ANDREWS"),
new Customer("MICHAEL", "AUSTIN"),
new Customer("MICHAEL", "AMATO")};
Here is the LINQ query without using Lambda expressions for sort data against multiple fields.
var sortedCustomers = from customer in customers
orderby customer.FirstName, customer.LastName
select customer;
How can we write this with Lambda expressions? Most of developers write it as below.
var orderBy = customers.OrderBy(c => c.FirstName).OrderBy(c => c.LastName);
But this is not gives expected result. Second OrderBy command executes over the previously sorted collection and effectively it will reorder the sequence completely two times. Effectively it will sort according to last field. Following image will shows the results of two queries.
So, what is the correct way to implement this? We can do it using both OrderBy and ThenBy clause.
Use OrderBy clause for most important field and use ThenBy clause for others. It will be like below format.
Collection.OrderBy().ThenBy().ThenBy()…
var thenBy = customers.OrderBy(c => c.FirstName).ThenBy(c => c.LastName);
Here is the result..