Question

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

Was it helpful?

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

OTHER TIPS

public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(this IEnumerable<TValue> seq, Func<TValue, TKey> keySelector)
{
    var dict = new SortedDictionary<TKey, TValue>();
    foreach(TValue item in seq)
    {
        dict.Add(keySelector(item), item);
    }

    return dict;
}

then you can use it as

SortedDictionary<DateTime, SpecialEvent> sortedEvents = list.ToSortedDictionary(r => r.Date);

Please note that SortedDictionary does not support duplicate keys. If you have two or more events with the same date you'll end up with an ArgumentException saying: An entry with the same key already exists.

A better approach is therefore probably to just sort your list of events:

list.Sort((a, b) => a.Date.CompareTo(b.Date));

This will perform an efficient in-place quick sort of your events. The result is that the list of events is sorted by date in ascending order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top