Reputation: 359
I have a list of arrays that contains multiple arrays. Each array has 2 indexes. First, I want to loop the list. Then I want to loop the array inside the list.
How can I do that ?
I tried to use this way, but it doesn't work:
1. foreach (string[] s in ArrangList1)
2. {
3. int freq1 = int.Parse(s[1]);
4. foreach (string[] s1 in ArrangList)
5. {
6. int freq2 = int.Parse(s1[1]);
7. if (freq1 < freq2)
8. {
9. backup = s;
10. index1 = ArrangList1.IndexOf(s);
11. index2 = ArrangList.IndexOf(s1);
12. ArrangList[index1] = s1;
13. ArrangList[index2] = s;
14. }
15. backup = null;
16. }
17. }
It give me error in line 4.
I try to do the loop using other way, but I don't know how to continue.
for (int i = 0; i < ArrangList1.Count; i++)
{
for (int j = 0; j < ArrangList1[i].Length; j++)
{
ArrangList1[i][1];
}
}
I use C#.
How can I fix this problem?
Upvotes: 1
Views: 3044
Reputation: 52400
You can also use LINQ and one foreach loop:
// assuming ArrangList1 is List<string[]>
var query = from a in ArrangList1
from b in a
select b;
foreach (String s in query)
{
System.Console.Writeline(s);
}
Upvotes: 0
Reputation: 46903
The error in line4 might be due to a typo using ArrangList. I think you only have ArrangList1 defined. Regardless, the logic is wrong. If you have a list containing arrays, you want to do a foreach on the list, then a foreach on each list item (which is an array).
It's not clear what your types are, so I'm assuming that ArrangList is a list of string arrays.
foreach(string[] s in ArrangList1)
{
foreach(string innerS in s)
{
//now you have your innerString
Console.WriteLine(innerS);
}
}
In your second example,
You have a typo as well...
for (int i = 0; i < ArrangList1.Count; i++)
{
for (int j = 0; j < ArrangList1[i].Length; j++)
{
ArrangList1[i][1]; //the 1 here should be j
}
}
Upvotes: 4