IDictionary Add Or Update - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

IDictionary Add Or Update

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from w w  w  . j  a v  a2s . co m*/

public class Main{
        /// <summary>
        /// 
        /// </summary>
        public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue addValue, Func<TValue, TValue> updateValue)
        {
            TValue foundValue;
            if (!dictionary.TryGetValue(key, out foundValue))
            {
                dictionary.Add(key, addValue);
            }
            else
            {
                dictionary[key] = addValue = updateValue(foundValue);
            }
            return addValue;
        }
}

Related Tutorials