Access an Array inside of ArrayList in C#

Viewed 64

My doubt is that is possible to access the values of the array inside of arraylist? Example:

int[] intArray = new int[];
string[] stringArray = new string[];
stringArray[0] = "Bob";
stringArray[1] = "John";
stringArray[2] = "Alex";
intArray[0] = 5;
intArray[1] = 7;
intArray[2] = 13;
ArrayList listOfArrays = new ArrayList() {intArray , stringArray };

In that example, its possible to access (print) the value of array (inserting the index value) inside of ArrayList?

3 Answers

Your example does not compile. I took the liberty of changing the first 2 lines so that it would.

You can access specific arrays within the ArrayList by index, casting them as the array type that they are. Then, you can access individual elements by index.

The below example gets the string "Alex" from stringArray:

int[] intArray = new int[3];
string[] stringArray = new string[3];
stringArray[0] = "Bob";
stringArray[1] = "John";
stringArray[2] = "Alex";
intArray[0] = 5;
intArray[1] = 7;
intArray[2] = 13;
ArrayList listOfArrays = new ArrayList() { intArray, stringArray };

// Get the string[] by index from the ArrayList:
string[] nestedStringArray = (string[])listOfArrays[1];

// Access an element:
string alex = nestedStringArray[2];

// Or do the above 2 lines in a single line:
alex = ((string[])listOfArrays[1])[2];

If you are just exploring the language, then this should help. However, this is not likely to be a good solution to use in a real application. Storing a variety of types in a single object and then casting in order to access them is a recipe for major headaches.

If your exercise is asking to print all the values inside an array with respect to the number of elements inside an array use the for loop with : for(initializer; condition; iterator) in the example below

for(int i = 0; i <intArray.Count; i++){
Console.WriteLine(intArray[i]);
}

But i'd suggest that you clarify more in what you need in your question.

listOfArrays[1][2] would access the 3rd element of the stringArray. The first number access the outer array, and the second number access the inner array.

Related