从字典填充ConcurrentDictionary

本文关键字:ConcurrentDictionary 填充 字典 | 更新日期: 2024-10-20 02:43:10

如何填充从DictionaryConcurrentDictionary的数据。

我有以下内容,

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" },
};

并且i填充到类似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这样的内置扩展方法?

从字典填充ConcurrentDictionary

您可以将Dictionary<T>传递到其中一个ConcurrentDictionary<T>构造函数中。

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

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;
}
相关文章:
  • 没有找到相关文章