Can someone help by showing me how to sort a LINQ expression.
I have the following:
.OrderByDescending(item => item.RowKey)
.Select((t, index) => new City.Grid()
{
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Row = index + 1,
ShortTitle = t.ShortTitle,
})
What I would like to do is to do a sort on the following:
1) First four characters or field RowKey
2) ShortTitle
I am not sure how to do a sort on just a few characters and also not sure how to do a secondary sort.
Always make use of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which then exposes the methods ThenBy() and ThenByDescending() . This means that we can OrderBy on multiple fields by chaining OrderBy() and ThenBy() together.
Try OrderBy(x => x. Col1). ThenBy(x => x. Col2) .
For LINQ to Objects, it's a stable quicksort that is used.
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.
For the first four characters, include that in your existing statement, then add the ShortTitle afterwards
.OrderByDescending(item => item.RowKey.Substring(0,4))
.ThenBy(item => item.ShortTitle)
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