在C#中,将List<T>转换为SortedDictionary<string, T>的最佳方法是什么?

4

我有一个SpecialEvent对象列表

List<SpecialEvent>

我希望将其转换为已排序的字典,其中键是SpecialEvent.Date,值是SpecialEvent对象。
我基本上需要像这样的东西:
list.ToDictionary(r=>r.Date, r=>r)

但它转换为排序字典而不是普通字典。
3个回答

9
您可以使用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));
}

2
这首先基于哈希码建立了整个Dictionary<,>,然后创建另一个对象,即基于IComparable<>SortedDictionary<,>,第一个Dictionary<,>被丢弃。它会工作(除了在GetHashCodeEquals不能“分离”被CompareTo视为不同实例的假设情况下),但是李的答案似乎更优雅。 - Jeppe Stig Nielsen

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

0
请注意,SortedDictionary 不支持重复的键。如果您有两个或更多具有相同日期的事件,则会出现一个 ArgumentException,其中写着:已经存在具有相同键的条目。

因此,更好的方法可能是仅对事件列表进行排序:

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

这将执行一个高效的原地快速排序,对您的事件进行排序。结果是按日期升序排序的事件列表。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接