I have written Dictionary which returns default value if the key is missing in the dictionary.
You simply pass lambda function for returning value when the key is missing in Dictionary to its constructor.
This is how to use....
You simply pass lambda function for returning value when the key is missing in Dictionary to its constructor.
using System; using System.Collections.Generic; namespace Utility.Data { public class DefaultDictionary<TKey, TValue> : Dictionary<TKey, TValue> { private readonly Func<TKey, TValue> defaulter; public DefaultDictionary(Func<TKey, TValue> defaulter) { this.defaulter = defaulter; } public TValue GetDefaultValueIfMissing(TKey key){ if (ContainsKey(key)) { return this[key]; } return defaulter(key); } } }
This is how to use....
var dict = new DefaultDictionary<string, IList<string>>((key) => new List<string>()); // should return empty list var list = dict.GetDefaultValueIfMissing("key1");
コメント