Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order by a specific number first then show all rest in order

If i have a list of numbers:

1,2,3,4,5,6,7,8 

and I want to order by a specific number and then show the rest. For example if i pick '3' the list should be:

3,1,2,4,5,6,7,8 

Looking for linq and c#. Thank you

like image 326
vts Avatar asked Mar 29 '12 21:03

vts


People also ask

How do I sort a 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.

What is difference between OrderBy and ThenBy in LINQ?

The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

How do I get data in descending order in LINQ?

If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

How is the order of LINQ query in C#?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.


1 Answers

You can use a comparison in OrderBy or ThenBy to perform a conditional sorting.

list.OrderByDescending(i => i == 3).ThenBy(i => i); 

I use OrderByDescending because i want matching results first(true is "higher" than false).

like image 115
Tim Schmelter Avatar answered Sep 20 '22 01:09

Tim Schmelter