在C#中的并发字典中交换键和值

在C#中的“并发字典”中是否可以交换键和值?我知道对于Dictionary类型,它可能类似于

dictionary = dictionary.ToDictionary(x => x.Value,x => x.Key);

ConcurrentDictionary中有相似之处吗?

hhjuly 回答:在C#中的并发字典中交换键和值

您不能直接将Dictionary转换或转换为ConcurrentDictionary。 购买可以用字典创建ConcurrentDictionary,请检查此构造函数

public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey,TValue>> collection);

看看你说的LINQ的扩展方法

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

因此,如果DictionaryIEnumerable<KeyValuePair<TKey,TValue>>具有兼容性

解决方案1 ​​

只需使用LINQ的ToDictionary扩展方法

var concurrentDict = new ConcurrentDictionary<string,string>();
/* Add some items */
bool firstItem = concurrentDict.TryAdd("1","First");  //returns true
bool secondItem = concurrentDict.TryAdd("2","Second");  //returns  true

/* Swaping Value <-> Key to new Dictionary */
Dictionary<string,string> normalDict = concurrentDict.ToDictionary(x => x.Value,x => x.Key);

/* creating ConcurrentDictionary */
var newConcurrentDict = new ConcurrentDictionary<string,string>(normalDict);

解决方案2

线程安全如何?

您可以使用自定义扩展方法(如LINQ)

var concurrentDict = new ConcurrentDictionary<string,x => x.Key);

/* creating ConcurrentDictionary */
var newConcurrentDict = normalDict.ToConcurrentDictionary();

扩展方法

参考https://stackoverflow.com/a/27064366/1669574

public static class ConcurrentDictionaryExtensions
{
    public static ConcurrentDictionary<TKey,TElement> ToConcurrentDictionary<TSource,TElement> elementSelector,IEqualityComparer<TKey> comparer)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");

        ConcurrentDictionary<TKey,TElement> d = new ConcurrentDictionary<TKey,TElement>(comparer);
        foreach (TSource element in source)
            d.TryAdd(keySelector(element),elementSelector(element));

        return d;
    }

    public static ConcurrentDictionary<TKey,TSource> ToConcurrentDictionary<TSource,TKey>(
        this IEnumerable<TSource> source,TKey> keySelector)
    {
        return ToConcurrentDictionary<TSource,TSource>(source,keySelector,IdentityFunction<TSource>.Instance,null);
    }

    public static ConcurrentDictionary<TKey,IEqualityComparer<TKey> comparer)
    {
        return ToConcurrentDictionary<TSource,comparer);
    }

    public static ConcurrentDictionary<TKey,TElement> elementSelector)
    {
        return ToConcurrentDictionary<TSource,TElement>(source,elementSelector,null);
    }

    internal class IdentityFunction<TElement>
    {
        public static Func<TElement,TElement> Instance
        {
            get { return x => x; }
        }
    }
}
本文链接:https://www.f2er.com/3091793.html

大家都在问