1

I created a list of arrays. But i am trying to access a specific index to pull the specific array so i can loop through. and get values from it. I am not even sure how to start the code.my list of arrays has items each with 1 aray with 5 valuse. Any suggestions?

2
  • 1
    It would help to know what language you're using! Commented Jun 30, 2013 at 8:01
  • 4
    You should post a snippet of your existing code. Commented Jun 30, 2013 at 8:02

3 Answers 3

2

How about something like this

List<int[]> l = new List<int[]>();
l.Add(new int[] { 1, 2, 3 });
l.Add(new int[] { 2, 3, 4 });
l.Add(new int[] { 3, 4, 5 });
int a = l[2][2]; // a = 5
Sign up to request clarification or add additional context in comments.

1 Comment

This shows the OP how to access a given element of a given array in the list, but not how to loop through a given array in the list, which is what they seem to be asking.
1

You can use the index in the List to loop through a specific array, if you know it's index.

For example, say you have a List named listOfArrays, and you want to loop through the second array:

foreach (int element in listOfArrays[1])
{
    // do something with the array
}

listOfArrays[1] will return the int[] in the second position in the List.

Alternatively, you could loop through the entire list and process each array like this:

foreach (int[] arr in listOfArrays)
{

    foreach (int element in arr)
    {

        // do something with the array
    }
}

But it sounds like you're looking to simply access a specified array in the list, not all of them.

Comments

0

Hope, some examples help you

List<int[]> myList = new List<int[]>(); // <- MyList is list of arrays of int

// Let's add some values into MyList; pay attention, that arrays are not necessaily same sized arrays:

myList.Add(new int[] {1, 2, 3});
myList.Add(new int[] {4, 5, 6, 7, 8});
myList.Add(new int[] {}); // <- We can add an empty array if we want
myList.Add(new int[] {100, 200, 300, 400});

// looping through MyList and arrays 

int[] line = myList[1]; // <- {4, 5, 6, 7, 8}
int result = line[2]; // <- 6

// let's sum the line array's items: 4 + 5 + 6 + 7 + 8

int sum = 0;

for (int i = 0; i < line.Length; ++i)
  sum += line[i];

// another possibility is foreach loop:
sum = 0;

foreach(int value in line) 
  sum += value;   

// let's sum up all the arrays within MyList
totalSum = 0;

for (int i = 0; i < myList.Count; ++i) {
  int[] myArray = myList[i];

  for (int j = 0; j < myArray.Length; ++j)
    totalSum += myArray[j];  
}

// the same with foreach loop
totalSum = 0;

foreach(int[] arr in myList)
  foreach(int value in arr) 
    totalSum += value; 

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.