1

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.

4
  • 5
    use a generic list List<string> instead of ArrayList. Commented May 28, 2020 at 8:08
  • 2
    What is the reason for using ArrayList rather than List<T>? Commented May 28, 2020 at 8:08
  • a) ArrayList is deprecated for List<T>. b) It didn't work is not a helpful error description. Commented May 28, 2020 at 8:49
  • As the ArrayList documentation itself says - "We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List<T> class. The ArrayList class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance." Commented May 28, 2020 at 14:43

2 Answers 2

4

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.