Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List except one entry with LINQ

Tags:

c#

sorting

linq

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?

like image 357
daniel Avatar asked Apr 29 '13 11:04

daniel


1 Answers

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();
like image 148
George Duckett Avatar answered Oct 23 '22 10:10

George Duckett