IDictionary Get Or Add - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

IDictionary Get Or Add

Demo Code


using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System;//from   ww  w . java  2  s.c  o m

public class Main{
        // Get a value from the dictionary, or add one if not found.
      public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> create)
      {
         // Try to find the value in the dictionary.
         TValue result;
         if (!dict.TryGetValue(key, out result))
         {
            // Not found, so create using delegate and add.
            result = create();
            dict.Add(key, result);
         }

         return result;
      }
}

Related Tutorials