Dictionary GetOrAdd

public static TValue GetOrAdd<TKey,TValue>(
   this Dictionary<TKey,TValue> dictionary,
   TKey key,
   Func<TKey, TValue> valueFactory)
{
   TValue value;
   if (!dictionary.TryGetValue(key, out value))
   {
       value = valueFactory(key);
       dictionary.Add(key, value);
   }
   return value;
}

public static TValue AddOrUpdate<TKey,TValue>(
   this Dictionary<TKey,TValue> dictionary,
   TKey key,
   Func<TKey, TValue> addValueFactory,
   Func<TKey, TValue, TValue> updateValueFactory)
{
   TValue value;
   if (dictionary.TryGetValue(key, out value))
   {
       value = updateValueFactory(key, value);
   }
   else
   {
       value = addValueFactory(key);
   }
   dictionary[key] = value;
   return value;
}

 

posted on 2017-12-15 15:31  武胜-阿伟  阅读(855)  评论(0编辑  收藏  举报