I want to order a List of strings but one string in the list should always be at the beginning and not sorted. What is the easiest way to do this with LINQ?
//should be ordered in: first, a,b,u,z:
List<string> l = {"z","u","first","b","a"};
There is no prepend method or something in LINQ, is there?
l = l.OrderBy(i => i != "first").ThenBy(i => i).ToList();
The trick here is to order by whether the item in question is your special item, then order by your item as you normally would.
Since you said you want to order a list (with linq) don't forget to assign the result of the query back to the list.
You also asked about a prepend method, how about this:
l = new[] { "first" }.Concat(l).ToList();
You could easily make it an extension method:
public static class LinqExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> query, T item)
{
return new[] { item }.Concat(query);
}
}
called as:
l = l.Prepend("first").ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With