Linq Order by a specific number first then show all rest in order
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
).
A couple of answers already sort the last few numbers (which may be correct since you're only showing an already sorted list). If you want the "unselected" numbers to be displayed in their original, not necessarily sorted order instead of sorted, you can instead do;
int num = 3;
var result = list.Where(x => x == num).Concat(list.Where(x => x != num));
As @DuaneTheriot points out, IEnumerable's extension method OrderBy does a stable sort and won't change the order of elements that have an equal key. In other words;
var result = list.OrderBy(x => x != 3);
works just as well to sort 3 first and keep the order of all other elements.
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));