Any better way to convert an array to a parallel dictionary using linq or IEnumarable?

I have an Array object of a Person object and I want to convert it to ConcurrentDictionary . There is an extension method for converting Array to Dictionary . Is there any extension method for converting Array to 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); 

Any similar extension method / lambda expression to convert Array to ConcurrentDictionary ?

+6
source share
3 answers

Of course, use a constructor that accepts IEnumerable<KeyValuePair<int,Person>> :

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

var points to ConcurrentDictionary<int,Person> .

If you intend to create an extension method, as Wasp suggested, I would recommend using the following version, which offers a slightly smoother syntax:

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

Usage is similar to ToDictionary , creating a constant feel:

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

You can easily write your own extension method, for example, for example:

 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))); } } 
+9
source

There is a constructor that accepts IEnumerable<KeyValuePair<TKey,TValue>>

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

Source: https://habr.com/ru/post/925254/


All Articles