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?
-
1It would help to know what language you're using!Daniel Buckmaster– Daniel Buckmaster2013-06-30 08:01:09 +00:00Commented Jun 30, 2013 at 8:01
-
4You should post a snippet of your existing code.static_rtti– static_rtti2013-06-30 08:02:42 +00:00Commented Jun 30, 2013 at 8:02
Add a comment
|
3 Answers
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
1 Comment
Tim
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.
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
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;