使用linq或IEnumerable将数组转换为并发字典的任何更好的方法

本文关键字:字典 并发 任何 方法 更好 转换 linq IEnumerable 数组 使用 | 更新日期: 2025-04-30 14:32:33

我有一个Person对象的Array,我想将它转换为ConcurrentDictionary。有一种将Array转换为Dictionary的扩展方法。有没有将Array转换为ConcurrentDictionary的扩展方法?

public class Person
{
    public Person(string name, int age)
    {
        Name =name;
        Age = age;
    }
    public string Name { get; set; }
    public int Age { get; set; }
}
Dictionary<int, Person> PersonDictionary = new Dictionary<int, Person>(); 
Person[] PersonArray = new Person[]
{
    new Person("AAA", 30),
    new Person("BBB", 25),
    new Person("CCC",2),
    new Person("DDD", 1)
};
PersonDictionary = PersonArray.ToDictionary(person => person.Age);

是否有类似的扩展方法/lambda表达式用于将Array转换为ConcurrentDictionary

使用linq或IEnumerable将数组转换为并发字典的任何更好的方法

当然,使用接受IEnumerable<KeyValuePair<int,Person>>:的构造函数

var personDictionary = new ConcurrentDictionary<int, Person>
                       (PersonArray.ToDictionary(person => person.Age));

CCD_ 11将该类型推断为CCD_。

如果你要像Wasp建议的那样创建一个扩展方法,我建议你使用以下版本,它提供了一个更流畅的语法:

public static ConcurrentDictionary<TKey, TValue> ToConcurrentDictionary<TKey, TValue> 
(this IEnumerable<TValue> source, Func<TValue, TKey> valueSelector)
{
    return new ConcurrentDictionary<TKey, TValue>
               (source.ToDictionary(valueSelector));
}

用法类似于ToDictionary,营造出一致的感觉:

var dict = PersonArray.ToConcurrentDictionary(person => person.Age);

您可以非常容易地编写自己的扩展方法,例如:

public static class DictionaryExtensions
{
    public static ConcurrentDictionary<TKey, TValue> ToConcurrentDictionary<TKey, TValue>(
        this IEnumerable<KeyValuePair<TKey, TValue>> source)
    {
        return new ConcurrentDictionary<TKey, TValue>(source);
    }
    public static ConcurrentDictionary<TKey, TValue> ToConcurrentDictionary<TKey, TValue>(
        this IEnumerable<TValue> source, Func<TValue, TKey> keySelector)
    {
        return new ConcurrentDictionary<TKey, TValue>(
            from v in source 
            select new KeyValuePair<TKey, TValue>(keySelector(v), v));
    }
    public static ConcurrentDictionary<TKey, TElement> ToConcurrentDictionary<TKey, TValue, TElement>(
        this IEnumerable<TValue> source, Func<TValue, TKey> keySelector, Func<TValue, TElement> elementSelector)
    {            
        return new ConcurrentDictionary<TKey, TElement>(
            from v in source
            select new KeyValuePair<TKey, TElement>(keySelector(v), elementSelector(v)));
    }
}

有一个构造函数接受IEnumerable<KeyValuePair<TKey,TValue>>

IDictionary<int,Person> concurrentPersonDictionary = 
  new ConcurrentDictionary<int,Person>(PersonArray.ToDictionary(person => person.Age));