Populate Concurrent Dictionary from Dictionary

Total Post:135

 1888  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?

  1. Post:145

    Re: Populate Concurrent Dictionary from Dictionary

    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>
        var dictionary =new ConcurrentDictionary<TKey, TElement>();
        foreach (TSource local in source)
            dictionary.TryAdd(keySelector(local), elementSelector(local));
        return dictionary;

      Modified On Apr-04-2018 12:09:18 AM