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

leo*_*ora 3 c# collections sorteddictionary

我在列表中有一个SpecialEvent对象列表

List<SpecialEvent>
Run Code Online (Sandbox Code Playgroud)

我想将它转换为一个排序字典,其中键是SpecialEvent.Date,值是SpecialEvent对象

我基本上想要这样的东西:

list.ToDictionary(r=>r.Date, r=>r)
Run Code Online (Sandbox Code Playgroud)

但是转换为排序字典而不是常规字典

pas*_*ein 8

您可以使用以下构造函数SortedDictionary:

var dict = new SortedDictionary<string, SpecialEvent>(list.ToDictionary(r => r.Date, r => r));
Run Code Online (Sandbox Code Playgroud)

或者,作为通用方法:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 这首先基于哈希码构建了一个完整的`Dictionary&lt;,&gt;`,只是为了创建另一个对象,即基于`IComparable&lt;&gt;`的corse的`SortedDictionary&lt;,&gt;`,以及第一个`Dictionary&lt;,&gt; ` 然后再次丢弃。它会起作用(除非在假设情况下,`GetHashCode` 和 `Equals` 不会“分离”被 `CompareTo` 认为不同的实例),但 Lee 的答案似乎更优雅。 (2认同)

Lee*_*Lee 5

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用它作为

SortedDictionary<DateTime, SpecialEvent> sortedEvents = list.ToSortedDictionary(r => r.Date);
Run Code Online (Sandbox Code Playgroud)