[英]Using more than one object to iterate though 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 iterate though the list as follows - but this only iterates 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);
}
If the lists are of the same size, you can use Enumerable.Zip
: 如果列表大小相同,则可以使用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);
}
If you want to sequentially iterate through the two lists, you can use IEnumerable<T>.Union(IEnumerable<T>)
extension method : 如果要依次遍历这两个列表,可以使用IEnumerable<T>.Union(IEnumerable<T>)
扩展方法 :
IEnumerable<string> union = list[0].Union(list[1]);
foreach(string str int union)
{
DoSomething(str);
}
If you want a matrix of combination, 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);
}
You can try the following code. 您可以尝试以下代码。 It also works if the sizes differ. 如果尺寸不同,它也可以使用。
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);
}
}
使用LINQ代替:
foreach (var s in list.SelectMany(l => l)) { Console.WriteLine(s); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.