-1

I need to use a dictionary inside this list

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

So far I have tried to populate it with this

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

and display it to the console

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

I got System.ArgumentOutOfRangeException error on run, any fixes?

Yogesh Patel
  • 818
  • 2
  • 12
  • 26
Billy Anthony
  • 49
  • 1
  • 8

3 Answers3

3

You need to use Add to add items to a List in C#.

Change your code to:

    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"]);
    }

However, I'd recommend creating a class to represent Person:

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

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

And doing

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);
}
haldo
  • 14,512
  • 5
  • 46
  • 52
1
People.Add(new Dictionary<string, string>());

Don´t you need to add the first entry in the List first?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
GrabnaMax
  • 47
  • 7
1

replace

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

with

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

You get a System.ArgumentOutOfRangeException because you access a not existing item.

fubo
  • 44,811
  • 17
  • 103
  • 137