简体   繁体   English

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

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

I have a list of SpecialEvent objects in a list 我在列表中有一个SpecialEvent对象列表

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 我想将它转换为一个排序字典,其中键是SpecialEvent.Date,值是SpecialEvent对象

I basically want something like: 我基本上想要这样的东西:

list.ToDictionary(r=>r.Date, r=>r)

but that converts to sorted dictionary instead of a regular one 但是转换为排序字典而不是常规字典

You could use the constructor of SortedDictionary : 您可以使用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));
}
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);

Please note that SortedDictionary does not support duplicate keys. 请注意, SortedDictionary不支持重复键。 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. 如果您有两个或多个具有相同日期的事件,则最终会出现ArgumentException具有相同键的条目已存在。

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. 结果是事件列表按日期按升序排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM