迭代两个列表或数组在C#1 foreach语句 [英] Iterate two Lists or Arrays with one ForEach statement in C#

查看:436
本文介绍了迭代两个列表或数组在C#1 foreach语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是常识:

如果我有两个,比方说,列表,我想用相同的foreach循环遍历两者,我们能做到吗?

If I have two, let's say, List, and I want to iterate both with the same foreach loop, can we do that?

修改

只是为了澄清,我想做到这一点:

Just to clarify, I wanted to do this:

List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };

for(int i = 0; i < listA.Count; i++)
    listB[i] = listA[i];

但在foreach =)

But with a foreach =)

推荐答案

这就是所谓的的邮编操作,将在.NET 4的支持。

This is known as a Zip operation and will be supported in .NET 4.

就这样,你就可以写类似:

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}


至于匿名类型的命名字段另外,您也可以在括号节约用一个数组和它的静态Tuple.Create帮手:


As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

这篇关于迭代两个列表或数组在C#1 foreach语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆