Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort on multiple fields with LINQ?

Tags:

c#

linq

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.

like image 819
Alan2 Avatar asked Jun 13 '12 08:06

Alan2


People also ask

How do I sort multiple columns in LINQ?

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.

How do I sort by two columns in Entity Framework?

Try OrderBy(x => x. Col1). ThenBy(x => x. Col2) .

What sorting algorithm does LINQ use?

For LINQ to Objects, it's a stable quicksort that is used.

How would you sort the list in ascending order 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

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)
like image 138
Jon Egerton Avatar answered Oct 02 '22 16:10

Jon Egerton