In LINQ (Language Integrated Query), you can perform sorting operations on collections using the OrderBy
, OrderByDescending
, ThenBy
, and ThenByDescending
methods. These methods allow you to sort the elements of a sequence based on one or more keys.
Here's an overview of how you can perform sorting in LINQ:
- OrderBy: This method sorts the elements of a sequence in ascending order based on a key.
var sortedList = collection.OrderBy(item => item.Property);
In the above example, collection
is the original sequence, item => item.Property
is a lambda expression that defines the key to sort on (replace Property
with the actual property or field name you want to sort by), and sortedList
will contain the sorted sequence.
- OrderByDescending: This method sorts the elements of a sequence in descending order based on a key.
var sortedList = collection.OrderByDescending(item => item.Property);
The usage is similar to OrderBy
, but the elements will be sorted in descending order.
- ThenBy: This method is used for secondary sorting. It sorts the elements in ascending order based on a second key, after an initial sorting has been performed.
var sortedList = collection.OrderBy(item => item.FirstProperty)
.ThenBy(item => item.SecondProperty);
In the above example, the elements are first sorted by FirstProperty
, and then for items with the same FirstProperty
value, they are sorted by SecondProperty
.
- ThenByDescending: This method is similar to
ThenBy
, but it performs a secondary sorting in descending order.
var sortedList = collection.OrderBy(item => item.FirstProperty)
.ThenByDescending(item => item.SecondProperty);
In this case, the elements are first sorted by FirstProperty
, and for items with the same FirstProperty
value, they are sorted by SecondProperty
in descending order.
Note that the OrderBy
, OrderByDescending
, ThenBy
, and ThenByDescending
methods return a new sequence with the sorted elements, and the original collection remains unchanged. If you want to sort the elements in place, you can use the List<T>.Sort
method.
Comments
Post a Comment