是否有净拉链样的方法?拉链、方法

2023-09-03 15:50:29 作者:拿得起却放不下ゝ

在Python中有一个非常整洁的函数调用拉链可通过使用两个列表迭代在同一时间:

In Python there is a really neat function called zip which can be used to iterate through two lists at the same time:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
    print v1 + " " + v2

以上code建议立即进行删除产生如下:

The above code shoul produce the following:

1 a
2 b
3 c

我不知道是否有像它提供了一种方法,净?我正在考虑写我自己,但没有点,如果它已经可用。

I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.

推荐答案

更​​新:它是内置在C#4中的 System.Linq.Enumerable.Zip方法

Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip Method

下面是一个C#3的版本:

Here is a C# 3 version:

IEnumerable<TResult> Zip<TResult,T1,T2>
    (IEnumerable<T1> a,
     IEnumerable<T2> b,
     Func<T1,T2,TResult> combine)
{
    using (var f = a.GetEnumerator())
    using (var s = b.GetEnumerator())
    {
        while (f.MoveNext() && s.MoveNext())
            yield return combine(f.Current, s.Current);
    }
}

掉落的C#2版本,因为它显示出它的年龄。

Dropped the C# 2 version as it was showing its age.