列表中的c#字典[重复]

问题描述 投票:-1回答:3

这个问题在这里已有答案:

我需要在这个列表中使用字典

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错误,有任何修复?

c# list dictionary
3个回答
3
投票

您需要使用Add将项目添加到C#中的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;
    }
}

并做

var people = new List<Person>();
var person = new Person("1", "John");
people.Add(person);
for (int i = 0; i < people.Count; i++)
{
    Console.WriteLine(people[i].ID);
    Console.WriteLine(people[i].Name);
}

1
投票

更换

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

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

你得到一个System.ArgumentOutOfRangeException,因为你访问一个不存在的项目。


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

你不需要先在List中添加第一个条目吗?

© www.soinside.com 2019 - 2024. All rights reserved.