首页 > 解决方案 > C# 字典列表列表

问题描述

我有一个字典列表列表。如何向此数据结构添加字典?

public class Messages
{
    public List<List<Dictionary<string, string>>> store = new List<List<Dictionary<string, string>>>();

...
...
...

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("ID", "12345");
    dict.Add("Comment", "Hello");
   
int Count = 0;

messages.store[Count].Add(dict); // ??? 

标签: c#

解决方案


问题可能是messages.store不包含Count + 1您可以访问的元素messages.store[Count]。您需要首先确保该元素存在。

int Count = 0;
while (messages.store.Count <= Count) {
    List<Dictionary<string, string>> emptyListOfDict = new List<Dictionary<string, string>>();
    messages.store.Add(emptyListOfDict);
}
messages.store[Count].Add(dict);

将其作为方法包含在类中而不是使用外部代码来检查它可能更有意义。

public class Messages {
    public List<List<Dictionary<string, string>>> store = new List<List<Dictionary<string, string>>>();

    public void AddStore(int location, Dictionary<string, string> dict) {
        while (messages.store.Count <= Count) {
            List<Dictionary<string, string>> emptyListOfDict = new List<Dictionary<string, string>>();
            this.store.Add(emptyListOfDict);
        }
        this.store[location].Add(dict);
    }
}

...

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("ID", "12345");
dict.Add("Comment", "Hello");

messages.AddStore(0, dict);


推荐阅读