8

我有一个ArrayofPerson对象,我想将它转换为一个ConcurrentDictionary. Array有将 a 转换为 a的扩展方法Dictionary。是否有任何将 a 转换Array为 a 的扩展方法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 表达式用于将 a 转换Array为 a ConcurrentDictionary

4

3 回答 3

23

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

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

var将类型推断为ConcurrentDictionary<int,Person>.

如果您要按照 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);
于 2012-09-12T21:15:03.907 回答
12

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

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)));
    }
}
于 2012-09-12T21:23:26.830 回答
3

有一个构造函数需要IEnumerable<KeyValuePair<TKey,TValue>>

IDictionary<int,Person> concurrentPersonDictionary = 
  new ConcurrentDictionary<int,Person>(PersonArray.ToDictionary(person => person.Age));
于 2012-09-12T21:14:57.623 回答