Query Ordering - OrderBy() ThenBy() C# with Example
OrderByDescending() ThenByDescending() string[] names= { "mark", "steve", "adam" }; Ascending: Query Syntax var sortedNames = from name in names orderby name select name; Method Syntax var sortedNames = names.OrderBy(name => name); sortedNames contains the names in following order: "adam","mark","steve" Descending: Query Syntax var sortedNames = from name in names orderby name descending select name; Method Syntax var sortedNames = names.OrderByDescending(name => name); sortedNames contains the names in following order: "steve","mark","adam" Order by several fields Person[] people = { new Person { FirstName = "Steve", LastName = "Collins", Age = 30}, new Person { FirstName = "Phil" , LastName = "Collins", Age = 28}, new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 29}, new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 15} }; Query Syntax var sortedPeople = from person in people orderby person.LastName, person.FirstName, person.Age descending select person; Method Syntax sortedPeople = people.OrderBy(person => person.LastName) .ThenBy(person => person.FirstName) .ThenByDescending(person => person.Age); Result 1. Adam Ackerman 29 2. Adam Ackerman 15 3. Phil Collins 28 4. Steve Collins 30