我们可以在foreach中使用多个变量吗?

Ani*_*ish 12 c# asp.net-mvc-4

我们可以在foreach中使用多个变量吗?

foreach (var item1 in collection1;var items2 in collection2)
{

}
Run Code Online (Sandbox Code Playgroud)

我想这样做是因为我需要从数据库中获取两个集合并将它们都附加到ComboBox.

Axe*_*ger 13

使用LINQ连接数组,将结果放入匿名类型,然后迭代生成的集合.

var col = collection1.Join(collection2, x => x, y => y, (x, y) => new { X = x, Y = y });
foreach (var entry in col) {
    // entry.X, entry.Y
}
Run Code Online (Sandbox Code Playgroud)

编辑:

在发布答案时我假设collection1collection2包含不同的类型.如果它们包含相同类型或共享公共基类型,则有其他选择:

如果要允许重复:

collection1.Concat(collection2); // same type
collection1.select(x => (baseType)x).Concat(collection2.select(x => (baseType)x)); // shared base type
Run Code Online (Sandbox Code Playgroud)

没有重复:

collection1.Union(collection2); // same type
collection1.select(x => (baseType)x).Union(collection2.select(x => (baseType)x)); // shared base type
Run Code Online (Sandbox Code Playgroud)

表单框架4.0以后Zip可以替换原始解决方案:

collection1.Zip(collection2, (x, y) => new { X = x, Y = y });
Run Code Online (Sandbox Code Playgroud)

有关大多数可用LINQ funktions的概述,请参阅101 LINQ Samples.

如果没有LINQ,则使用两个分层的foreach循环(增加交互次数)或一个foreach循环来创建一个中间类型,第二个迭代中间项集合,或者如果集合中的类型相同,则将它们添加到列表中(使用AddRange)然后迭代这个新列表.

许多道路通向一个目标...由您决定选择一个.


Ste*_*ger 6

您可以压缩集合

foreach (var item in collection1.Zip(collection2, (a, b) => new {  A = a, B = b }))
{
  var a = item.A;
  var b = item.B;
  // ...
}
Run Code Online (Sandbox Code Playgroud)

这假设元素在相同的位置匹配(例如,collection1 中的第一个元素加入了 collecion2 的第一个元素)。这是相当有效的。


Col*_*inE 3

不可以,您不能在 foreach、in 循环中使用多个变量。检查语言参考。如果每个集合都有不同数量的物品,会发生什么?

如果您想迭代两个集合,请尝试使用联合:

foreach (var item1 in collection1.Union(collection2))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)