简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM