Linq Order by a specific number first, then show everything else 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 selected "3", the list should be:

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

We are looking for linq and C #. Thanks you

+63
sorting c # linq order
Mar 29 2018-12-12T00:
source share
4 answers

You can use the comparison in ThenBy or ThenBy to do conditional sorting.

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

I use OrderByDescending because I want to match the results first ( true "higher" than false ).

+136
Mar 29 2018-12-12T00:
source share

Maybe something like this:

 List<int> ls=new List<int>{1,2,3,4,5,6,7,8}; int nbr=3; var result= ls.OrderBy (l =>(l==nbr?int.MinValue:l)); 
+5
Mar 29 2018-12-12T00:
source share

Several answers are already sorting the last few numbers (which may be correct as you are showing an already sorted list). If you want the โ€œunallocatedโ€ numbers to be displayed in the original, optionally sorted order instead of sorting, you can do this instead:

 int num = 3; var result = list.Where(x => x == num).Concat(list.Where(x => x != num)); 

As @DuaneTheriot points out, the IEnumerable extension OrderBy method does stable sorting and does not reorder items that have the same key, in other words:

 var result = list.OrderBy(x => x != 3); 

works the same as sorting 3 first and preserving the order of all other elements.

+3
Mar 29 2018-12-12T00:
source share
 public static IEnumerable<T> TakeAndOrder<T>(this IEnumerable<T> items, Func<T, bool> f) { foreach ( var item in items.Where(f)) yield return item; foreach (var item in items.Where(i=>!f(i)).OrderBy(i=>i)) yield return item; } var items = new [] {1, 4, 2, 5, 3}; items.TakeAndOrder(i=> i == 4); 
+2
Mar 29 2018-12-12T00:
source share



All Articles