Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort IEnumerable List?

I have the following list:

IEnumerable<Car> cars; 

The Car object has a model and a year. I want to sort this list by model and then year (within model).

What is the best way of doing this?

like image 483
leora Avatar asked Jun 17 '10 14:06

leora


People also ask

How does LINQ OrderBy work?

A sorting operator arranges the elements of the collection in ascending or descending order. LINQ includes following sorting operators. Sorts the elements in the collection based on specified fields in ascending or decending order. Sorts the collection based on specified fields in descending order.

Does C# list maintain order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

How do I use ascending order in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.


1 Answers

var sortedCars = cars.OrderBy(c => c.Model).ThenBy(c => c.Year); 
like image 86
Anthony Pegram Avatar answered Oct 13 '22 00:10

Anthony Pegram