Linq Order by a specific number first then show all rest in order
Solution 1
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
).
Solution 2
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.
Solution 3
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));
Solution 4
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);
vts
Updated on January 24, 2020Comments
-
vts over 4 years
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
-
Duane Theriot about 12 yearsYou can accomplish the same thing with
list.OrderBy(i => i != 3)
. -
Tim Schmelter over 8 years@cracker: change
OrderByDescending
toOrderBy
ori == 3
toi != 3
-
Pranesh Janarthanan over 5 yearsif want to sort string column
myDataList.OrderByDescending(i => i.StringColumnValue[0] == filterStringValue[0]).ToList()
. i used your logic here. Based on filter starting letter, those results are displayed in the order with same starting letter -
Kevin over 4 yearsSorry for the necro comment, but this isn't a good idea. Because if the list contains any entries of int.MinValue, this approach isn't going to work.
-
Manish Joisar over 2 yearsSo integer collection works but object collection is not working, am i missing anything here ? object.OrderByDescending(m => m.id== 298).ThenBy(x => x.CreatedOn)
-
Tim Schmelter over 2 years@ManishJoisar: it works the same way. The point is that
m.id== 298
returns abool
which can betrue
orfalse
andOrderByDescending
will yield thetrue
-values first. Maybe the reason why you think that it doesn't work is somethingelse. Create a question, so others can help. -
Manish Joisar over 2 years