Reputation: 196539
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
Upvotes: 4
Views: 3994
Reputation: 144136
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);
Upvotes: 6
Reputation: 11344
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.
Upvotes: 0
Reputation: 5846
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));
}
Upvotes: 9