How do you convert a dictionary to a ConcurrentDictionary?

后端 未结 4 1089
眼角桃花
眼角桃花 2021-01-17 12:04

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

4条回答
  •  无人及你
    2021-01-17 12:29

    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.

提交回复
热议问题