Home > DeveloperSection > Forums > Populate Concurrent Dictionary from Dictionary
Chintoo Semi

Total Post:135

Posted on    December-18-2013 12:37 AM

 C# C# 

 1 Reply(s)
 1451  View(s)
Rate this:

How can I populate the data from Dictionary to Concurrent Dictionary.

I have following,

public class Employee


    public int Id { get; set; }

    public string Name { get; set; }


var names = new List<Employee>


    new Employee { Id = 1, Name = "Name1" },

    new Employee { Id = 1, Name = "Name1" },

    new Employee { Id = 2, Name = "Name2" },

    new Employee { Id = 3, Name = "Name3" },


And I populate to Dictionary like

Dictionary<int, List<Employee>> dict = names.GroupBy(n => n.Id).ToDictionary(g => g.Key, g => g.ToList());

and I want to create,

ConcurrentDictionary<int, List<Employee>> concDict

and I tried,

ConcurrentDictionary<int, List<Employee>> concDict = new ConcurrentDictionary<int, List<Employee>>();

dict.ToList().ForEach(e => concDict.TryAdd(e.Key, e.Value));

Is there any built-in extension method like .ToDictionary?

ezra heywood
ezra heywood

Total Post:145

Posted on    December-18-2013 1:18 AM

Hi Chintoo,

You can pass the Dictionary<T> into one of the ConcurrentDictionary<T> constructors.

I don't think there's an extension method to do it directly, but it shouldn't be too difficult to write one if you want to avoid all the extra object creation.

public static ConcurrentDictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)


    var dictionary = new ConcurrentDictionary<TKey, TElement>();

    foreach (TSource local in source)


        dictionary.TryAdd(keySelector(local), elementSelector(local));


    return dictionary;


Don't want to miss updates? Please click the below button!

Follow MindStick