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?
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.
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.
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.
var sortedCars = cars.OrderBy(c => c.Model).ThenBy(c => c.Year);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With