如何在.NET中创建字典列表?

Viv*_*vek 12 .net c# dictionary list

我正在尝试创建一个Dictionary<string,int>项目列表.我不确定如何在列表中添加项目以及如何在遍历列表时返回值.我想在C#中使用它,如下所示:

public List<Dictionary<string,int>> MyList= new List<Dictionary<string,int>>();
Run Code Online (Sandbox Code Playgroud)

Jaa*_*jan 23

我想这就是你要找的东西?

{
    MyList.Add(new Dictionary<string,int>());
    MyList.Add(new Dictionary<string,int>());
    MyList[0].Add("Dictionary 1", 1);
    MyList[0].Add("Dictionary 1", 2);
    MyList[0].Add("Dictionary 2", 3);
    MyList[0].Add("Dictionary 2", 4);
    foreach (var dictionary in MyList)
        foreach (var keyValue in dictionary)
            Console.WriteLine(string.Format("{0} {1}", keyValue.Key, keyValue.Value));
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你快乐,你应该接受别人的回答.欢迎来到SO! (8认同)

cal*_*zar 23

5年后发生了很多变化......您现在可以执行以下操作:

ListDictionary list = new ListDictionary();
list.Add("Hello", "Test1");
list.Add("Hello", "Test2");
list.Add("Hello", "Test3");
Run Code Online (Sandbox Code Playgroud)

请享用!

  • 从来没有听说过!惊人!非常感谢 :) (2认同)
  • 使用 System.Collections.Specialized; (2认同)