Using more than one object for iteration, although in foreach loops

I have a multidimensional list:

List<string>[] list = new List<string>[2]; list[0] = new List<string>(); list[1] = new List<string>(); 

And I repeat this list as follows - but it is only iterating through one list:

 foreach (String str in dbConnectObject.Select()[0]) { Console.WriteLine(str); } 

Although I want to be able to do something like:

 foreach (String str in dbConnectObject.Select()[0] & String str2 in dbConnectObject.Select()[1]) { Console.WriteLine(str + str2); } 
+4
source share
4 answers

If the lists are the same size, you can use Enumerable.Zip :

 foreach (var p in dbConnectObject.Select()[0].Zip(dbConnectObject.Select()[1], (a,b) => new {First = a, Second = b})) { Console.Writeline("{0} {1}", p.First, p.Second); } 
+6
source

If you want to IEnumerable<T>.Union(IEnumerable<T>) over these two lists sequentially, you can use the IEnumerable<T>.Union(IEnumerable<T>) extension method :

 IEnumerable<string> union = list[0].Union(list[1]); foreach(string str int union) { DoSomething(str); } 

If you need a combination matrix, you can join the lists:

 var joined = from str1 in list[0] from str2 in list[1] select new { str1, str2}; foreach(var combination in joined) { //DoSomethingWith(combination.str1, combination.str2); Console.WriteLine(str + str2); } 
+2
source

You can try the following code. It also works if the sizes are different.

 for (int i = 0; i < list[0].Count; i++) { var str0 = list[0][i]; Console.WriteLine(str0); if (list[1].Count > i) { var str1 = list[1][i]; Console.WriteLine(str1); } } 
0
source

Use LINQ instead:

foreach (var s in list.SelectMany(l => l)) { Console.WriteLine(s); }

-1
source