loris02
loris02

Reputation: 39

ArrayList in ArrayList in C#?

I want to have an ArrayList in an ArrayList. This is how I did it:

ArrayList arraylist1 = new ArrayList();

ArrayList arraylist2 = new ArrayList();
arraylist2.Items.Add("test1");
arraylist2.Items.Add("test2");

arraylist1.Items.Add(arraylist2);

Now how can I call the arraylist?

I tried it this way:

arraylist1[0][0].ToString()
arraylist1[0][1].ToString()

It didn't work. Does anyone have any other ideas?

Thanks.

Upvotes: 1

Views: 197

Answers (2)

Risto M
Risto M

Reputation: 2999

This way using Generic List<string> and List<List<string>> types found in System.Collections.Generic-namespace:

var listOfStrings = new List<string>();
listOfStrings.Add("test1");
listOfStrings.Add("test2");

var listOfStringLists = new List<List<string>>();
listOfStringLists.Add(listOfStrings);

Console.WriteLine(listOfStringLists[0][0]);
Console.WriteLine(listOfStringLists[0][1]);

Upvotes: 4

Ronald Korze
Ronald Korze

Reputation: 828

The array list you use just returns objects, so you'd have to cast the outer entry 1st: ((ArrayList)arraylist1[0])[0]

As it was already proposed above, better use the generic List

Upvotes: 0

Related Questions