Konrad
Konrad

Reputation: 24661

C# adding elements to list in the list (two dimensional list)

I have a list:

List <List <string>> aList = new List <List <string>> ();

I want add something to the list in this list like that:

aList [0].Add ("item");

But I get ArgumentOutOfRangeException, why?

Adding list to list works perfect:

List <string> testList = new List <string> ();
testList.Add ("item");
aList.Add (testList);

Without any bugs. What am I doing wrong?

Upvotes: 0

Views: 4812

Answers (4)

Konrad
Konrad

Reputation: 24661

Ok, I found a solution to my own question! I must add any list to my own list before I can do that because it's empty so I can't access the list which not exists.

List <string> testList = new List <string> ();
aList.Add (testList);
aList [0].Add ("item");

Without any errors.

Upvotes: 1

Maxim Fleitling
Maxim Fleitling

Reputation: 562

public class Row
{
    public  List<string> Elements { get; private set; }

    public Row()
    {
        Elements = new List<string>();
    }

    public Row(List<string> elements)
    {
        Elements = elements;
    }
}

Using :

List<Row> rows = new List<Row>();
        rows.Add(new Row( new List<string>(){"abc","abc","abc"}));
        rows.Add(new Row(new List<string>() { "xyz", "xyz", "xyz" }));

or

 Row row = new Row();
        row.Elements.Add("abc");
        row.Elements.Add("xyz");

       rows.Add(row);

You can not add elements to a list which is not instateated

Upvotes: 0

Jack
Jack

Reputation: 435

aList [0].Add ("value");

This fails as there is no List at position 0 to add your value to.

Try

aList [0] = new List<string>;
aList [0].Add ("value");

Upvotes: 0

Sunil Sistla
Sunil Sistla

Reputation: 66

The first statement adding with index assumed that the size of list is >=1 which is not. Just initialization doesn't create a sized list.

Upvotes: 2

Related Questions