Steven
Steven

Reputation: 211

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?

Upvotes: 13

Views: 8924

Answers (3)

Bob Vale
Bob Vale

Reputation: 18474

You will need to use the IDictionary constructor so use the ToDictionary extension method on your linq query and then use new SortedList(dictionary);

e.g.

 var list=new SortedList(query.ToDictionary(q=>q.KeyField,q=>q));

Upvotes: 6

aelena
aelena

Reputation: 86

Something like this works just fine

List<MyEntity> list = DataSource.GetList<MyEntity>(); // whatever data you need to get

SortedList<string, string> retList = new SortedList<string, string> ();

list.ForEach ( item => retList.Add ( item.IdField, item.Description ) );

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500875

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 });

Upvotes: 19

Related Questions