从Dictionary中填充ConcurrentDictionary

时间:2013-12-17 03:23:58

标签: c# linq dictionary

如何将数据从Dictionary填充到ConcurrentDictionary

我有以下,

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var names = new List<Employee> 
{
    new Employee { Id = 1, Name = "Name1" },
    new Employee { Id = 1, Name = "Name1" },
    new Employee { Id = 2, Name = "Name2" },
    new Employee { Id = 3, Name = "Name3" },
};

我填充到Dictionary喜欢,

Dictionary<int, List<Employee>> dict = names.GroupBy(n => n.Id).ToDictionary(g => g.Key, g => g.ToList());

我要创建,

ConcurrentDictionary<int, List<Employee>> concDict

我试过了,

ConcurrentDictionary<int, List<Employee>> concDict = new ConcurrentDictionary<int, List<Employee>>();
dict.ToList().ForEach(e => concDict.TryAdd(e.Key, e.Value));

是否有任何内置的扩展方法,例如.ToDictionary

1 个答案:

答案 0 :(得分:3)

您可以将Dictionary<T>传递给其中一个ConcurrentDictionary<T> constructors

我认为没有一种扩展方法可以直接进行,但如果你想避免所有额外的对象创建,那么编写一个扩展方法应该不会太难。

public static ConcurrentDictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
{
    var dictionary = new ConcurrentDictionary<TKey, TElement>();
    foreach (TSource local in source)
    {
        dictionary.TryAdd(keySelector(local), elementSelector(local));
    }
    return dictionary;
}