Search code examples
c#collectionssorteddictionary

In C#, what is the best way to convert a List<T> to a SortedDictionary<string, T>?


I have a list of SpecialEvent objects in a list

List<SpecialEvent>

and i want to convert it to a sorted dictionary where the key is the SpecialEvent.Date and the value is the SpecialEvent object

I basically want something like:

list.ToDictionary(r=>r.Date, r=>r)

but that converts to sorted dictionary instead of a regular one


Solution

  • You could use the constructor of SortedDictionary:

    var dict = new SortedDictionary<string, SpecialEvent>(list.ToDictionary(r => r.Date, r => r));
    

    Or, as a generic method:

    public static SortedDictionary<T1,T2> ToSortedDictionary<Tin,T1,T2>(this List<Tin> source, Func<Tin,T1> keyselector, Func<Tin,T2> valueselector)
    {
        return new SortedDictionary<T1,T2>(source.ToDictionary(keyselector, valueselector));
    }