列表内的C#词典

时间:2018-12-12 13:21:21

标签: c# list dictionary

我需要在此列表中使用字典

List<Dictionary<string, string>> People= new List<Dictionary<string, string>>();

到目前为止,我已经尝试以此填充它

People[0] = new Dictionary<string, string>();
People[0].Add("ID number", "1");
People[0].Add("Name", "John");

并将其显示在控制台上

for (int i = 0; i < People.Count; i++)
{
    Console.WriteLine(People[i]["ID number"]);
    Console.WriteLine(People[i]["Name"]);
}

我知道了 System.ArgumentOutOfRangeException运行时发生错误,是否有任何修复程序?

3 个答案:

答案 0 :(得分:3)

您需要使用[...] label_dicts = [] # Array that will contain all the EntityAnnotation dictionaries print('Labels:') for label in labels: # Write each label (EntityAnnotation) into a dictionary dict = {'description': label.description, 'score': label.score, 'mid': label.mid} # Populate the array label_dicts.append(dict) with open('labels.json', 'w') as fp: json.dump(label_dicts, fp) 将项目添加到C#中的Add

将代码更改为:

List

但是,我建议创建一个代表 List<Dictionary<string, string>> People= new List<Dictionary<string, string>>(); People.Add(new Dictionary<string, string>()); People[0].Add("ID Number", "1"); People[0].Add("Name", "John"); for (int i = 0; i < People.Count; i++) { Console.WriteLine(People[i]["ID Number"]); Console.WriteLine(People[i]["Name"]); } 的类:

Person

public class Person 
{
    public string ID { get; set;}
    public string Name { get; set; }

    public Person(string id, string name)
    {
        ID = id;
        Name = name;
    }
}

答案 1 :(得分:1)

People.Add(new Dictionary<string, string>());

您不需要先在列表中添加第一个条目吗?

答案 2 :(得分:1)

替换

People[0] = new Dictionary<string, string>();

使用

People.Add(new Dictionary<string, string>());

您获得System.ArgumentOutOfRangeException是因为您访问了不存在的项目。