I recently started to learn about LINQ and came across the OrderBy
extension method. This initially excited me because the syntax seemed much nicer than the Sort
method that we use all over the place for Generic Lists.
For example, when sorting a list of languages, we normally do something like:
neutralCultures.Sort((x, y) => x.EnglishName.CompareTo(y.EnglishName));
This works well, but I prefer the syntax of OrderBy
, which only requires that you pass in the property that you wish to sort by, like so:
neutralCultures.OrderBy(ci => ci.EnglishName);
The problem is that OrderBy
returns IOrderedEnumerable
, but I need List<T>
. So, I set out to extend the Sort
method for List<T>
using the same signature that is used for OrderBy
.
public static void Sort<TSource, TKey>(this List<TSource list, Func<TSource, TKey> keySelector)
{
list = list.OrderBy(keySelector).ToList<TSource>();
}
This would be called like:
neutralCultures.Sort(ci => ci.EnglishName);
Maybe I'm overlooking a simple implementation detail, but this code doesn't work. It compiles, but doesn't return an ordered list. I'm sure I can refactor this to make it work, but I was just wondering why setting list
within the extension method doesn't work.