I have seen how to convert a ConcurrentDictionary to a Dictionary, but I have a dictionary and would like to convert to a ConcurrentDictionary. How do I do that?... better
Why not write your own extension method:
public static class ConcurrentDictionaryExtensions {
public static ConcurrentDictionary ToConcurrentDictionary(this IEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) {
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
if (elementSelector == null) throw new ArgumentNullException("elementSelector");
ConcurrentDictionary d = new ConcurrentDictionary(comparer ?? EqualityComparer.Default);
foreach (TSource element in source)
d.TryAdd(keySelector(element), elementSelector(element));
return d;
}
public static ConcurrentDictionary ToConcurrentDictionary(this IEnumerable source, Func keySelector) {
return ToConcurrentDictionary(source, keySelector, IdentityFunction.Instance, null);
}
public static ConcurrentDictionary ToConcurrentDictionary(this IEnumerable source, Func keySelector, IEqualityComparer comparer) {
return ToConcurrentDictionary(source, keySelector, IdentityFunction.Instance, comparer);
}
public static ConcurrentDictionary ToConcurrentDictionary(this IEnumerable source, Func keySelector, Func elementSelector) {
return ToConcurrentDictionary(source, keySelector, elementSelector, null);
}
internal class IdentityFunction {
public static Func Instance
{
get { return x => x; }
}
}
}
Simply adopted the code from the .Net framework.