c# - 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); // ???
解决方案
问题可能是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);
推荐阅读
- java - 给定一个整数数组(长度为 n),使用 Java 中的递归查找并返回输入数组的所有子集
- html - 响应式 MaterializeCSS 设计
- java - 使用后置摄像头的人脸检测无法使用 camera2 API 正常工作
- python - 想要在数据被屏蔽时创建一个零数组,在数据未被屏蔽时创建一个数组
- python-3.x - 如何使用 python 检查是否在 Ubuntu 上安装了一个包
- python - 向python函数添加条件
- sql - Datagrid 不会随着使用 SELECT 语句创建的表的更改而动态更新
- python - 如何使用 python 中的“Dijkstra 算法”在图中遍历以找到源和目标之间的最短路径?
- python - 我可以在 python 中创建一个 txt 文件,名称为变量的字符串值吗?
- html - 如何批量删除段落中的不同文本值