Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq return SortedList

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?

like image 987
Steven Avatar asked Sep 14 '11 00:09

Steven


1 Answers

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 });
like image 155
Jon Skeet Avatar answered Oct 22 '22 22:10

Jon Skeet