I have an Array
of Person
object and I want to convert it to a ConcurrentDictionary
. There is extension method for converting an Array
to a Dictionary
. Is there any extension method for converting an Array
to 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);
Any similar extension method/lambda expression for converting an Array
to a ConcurrentDictionary
?
Sure, use the constructor that accepts an IEnumerable<KeyValuePair<int,Person>>
:
var personDictionary = new ConcurrentDictionary<int, Person>
(PersonArray.ToDictionary(person => person.Age));
var
infers the type to ConcurrentDictionary<int,Person>
.
If you're going to create an extension method, as Wasp suggested, I would recommend using the following version which offers a somewhat more fluent 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));
}
The usage is similar to the ToDictionary
, creating a consistent feel:
var dict = PersonArray.ToConcurrentDictionary(person => person.Age);
You can write your own extension method very easily, for example like these:
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)));
}
}
There is a constructor that takes IEnumerable<KeyValuePair<TKey,TValue>>
IDictionary<int,Person> concurrentPersonDictionary =
new ConcurrentDictionary<int,Person>(PersonArray.ToDictionary(person => person.Age));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With