Nikhil Nikhil - 2 months ago 12
C# Question

Any better way for converting array to concurrent dictionary using linq or IEnumarable?

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
?

Answer

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);
Comments