使用 Extension 方法构建新的集合类型(例如 DictList)
你可以创建扩展方法以提高嵌套集合的可用性,例如具有 List<T>
值的 Dictionary
。
请考虑以下扩展方法:
public static class DictListExtensions
{
public static void Add<TKey, TValue, TCollection>(this Dictionary<TKey, TCollection> dict, TKey key, TValue value)
where TCollection : ICollection<TValue>, new()
{
TCollection list;
if (!dict.TryGetValue(key, out list))
{
list = new TCollection();
dict.Add(key, list);
}
list.Add(value);
}
public static bool Remove<TKey, TValue, TCollection>(this Dictionary<TKey, TCollection> dict, TKey key, TValue value)
where TCollection : ICollection<TValue>
{
TCollection list;
if (!dict.TryGetValue(key, out list))
{
return false;
}
var ret = list.Remove(value);
if (list.Count == 0)
{
dict.Remove(key);
}
return ret;
}
}
你可以使用扩展方法如下:
var dictList = new Dictionary<string, List<int>>();
dictList.Add("example", 5);
dictList.Add("example", 10);
dictList.Add("example", 15);
Console.WriteLine(String.Join(", ", dictList["example"])); // 5, 10, 15
dictList.Remove("example", 5);
dictList.Remove("example", 10);
Console.WriteLine(String.Join(", ", dictList["example"])); // 15
dictList.Remove("example", 15);
Console.WriteLine(dictList.ContainsKey("example")); // False