C# Linq return SortedList

Steven picture Steven · Sep 14, 2011 · Viewed 7.3k times · Source

How can I get Linq in C# to return a SortedList given an IEnumerable? If I can't, is it possible to cast or transform the IEnumerable to a SortedList?

Answer

Jon Skeet picture Jon Skeet · Sep 14, 2011

The simplest way would probably be to create a dictionary using ToDictionary, and then call the SortedList<TKey, TValue>(dictionary) constructor. Alternatively, add your own extension method:

public static SortedList<TKey, TValue> ToSortedList<TSource, TKey, TValue>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     Func<TSource, TValue> valueSelector)
{
    // Argument checks elided
    SortedList<TKey, TValue> ret = new SortedList<TKey, TValue>();
    foreach (var item in source)
    {
        // Will throw if the key already exists
        ret.Add(keySelector(item), valueSelector(item));
    }
    return ret;
}

This will allow you to create SortedLists with anonymous types as the values:

var list = people.ToSortedList(p => p.Name,
                               p => new { p.Name, p.Age });