LoginSignup
1
1

More than 5 years have passed since last update.

【C#】任意個のIEnumerableをzipする

Last updated at Posted at 2017-11-04

はじめに

Pythonの zip(a, b) は、C#だと a.Zip(b, Tuple.Create) です。

Pythonの zip(a, b, c) は、C#にはたぶん用意されていない。なぜだ。不便だ。

無いなら作ろう

できた。

public static class MoreMoreEnumerable
{
    public static IEnumerable<T[]> Zip<T>(this IEnumerable<IEnumerable<T>> sources)
    {
        var enumerators = sources.Select(_ => _.GetEnumerator()).ToArray();
        while (enumerators.All(_ => _.MoveNext()))
            yield return enumerators.Select(_ => _.Current).ToArray();
    }
}

使用例

var a = new[] { 1, 2, 3 };
var b = new[] { 4, 5, 6 };
var c = new[] { 7, 8, 9 };
int[][] abc = new[] { a, b, c }.Zip().ToArray();
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1