簡體   English   中英

在C#中,轉換List的最佳方法是什么 <T> 到SortedDictionary <string, T> ?

[英]In C#, what is the best way to convert a List<T> to a SortedDictionary<string, T>?

我在列表中有一個SpecialEvent對象列表

List<SpecialEvent>

我想將它轉換為一個排序字典,其中鍵是SpecialEvent.Date,值是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));

這將對您的活動進行有效的就地快速排序。 結果是事件列表按日期按升序排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM