我为此写了一个字典扩展:
public static class DictionaryExtensions
{
public static void AddOrUpdate(this Dictionary<string, List<string>> targetDictionary, string key, string entry)
{
if (!targetDictionary.ContainsKey(key))
targetDictionary.Add(key, new List<string>());
targetDictionary[key].Add(entry);
}
}
现在您可以简单地添加或更新:
using System;
using System.Collections.Generic;
using DictionaryExtensions;
public class Program
{
public static void Main()
{
var newDic = new Dictionary<string, List<string>>();
newDic.AddOrUpdate("Alpha","Anton");
newDic.AddOrUpdate("Alpha","Boris");
newDic.AddOrUpdate("Beta","Doris");
newDic.AddOrUpdate("Delta","Emil");
newDic.AddOrUpdate("Alpha","Ceasar");
System.Console.Write(newDic["Alpha"][1].ToString());
}
}