我有一个SpecialEvent对象列表
List<SpecialEvent>
我希望将其转换为已排序的字典,其中键是SpecialEvent.Date,值是SpecialEvent对象。
我基本上需要像这样的东西:
list.ToDictionary(r=>r.Date, r=>r)
但它转换为排序字典而不是普通字典。
我有一个SpecialEvent对象列表
List<SpecialEvent>
list.ToDictionary(r=>r.Date, r=>r)
SortedDictionary
的构造函数:var dict = new SortedDictionary<string, SpecialEvent>(list.ToDictionary(r => r.Date, r => r));
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;
}
SortedDictionary<DateTime, SpecialEvent> sortedEvents = list.ToSortedDictionary(r => r.Date);
SortedDictionary
不支持重复的键。如果您有两个或更多具有相同日期的事件,则会出现一个 ArgumentException
,其中写着:已经存在具有相同键的条目。
因此,更好的方法可能是仅对事件列表进行排序:
list.Sort((a, b) => a.Date.CompareTo(b.Date));
这将执行一个高效的原地快速排序,对您的事件进行排序。结果是按日期升序排序的事件列表。
Dictionary<,>
,然后创建另一个对象,即基于IComparable<>
的SortedDictionary<,>
,第一个Dictionary<,>
被丢弃。它会工作(除了在GetHashCode
和Equals
不能“分离”被CompareTo
视为不同实例的假设情况下),但是李的答案似乎更优雅。 - Jeppe Stig Nielsen