LoginSignup
1
2

複数IEnumerableのZip関数

Posted at

欲しい機能

LinqのZip関数が2個ないし3個までしかまとめられない。
もっとたくさんのIEnumerableをまとめて先頭から返す関数がほしい。

例えば、時系列に沿ったデータが複数あって、
それを1日毎に合計・平均値を取りたいといった場合

図にすると下のような感じ

これを
image.png
こうしたい
image.png

早速だけど、実装

public static IEnumerable<IEnumerable<T>> Zip<T>(this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(s => s.GetEnumerator()).ToArray();
    if (enumerators.Length <= 0) yield break;
    while (enumerators.All(e => e.MoveNext()))
        yield return enumerators.Select(e => e.Current);
}

欠点とこれから

標準のZip関数と違って、同じ型しかまとめられない。
どちらかというと、行列の転置みたいな感じかな。関数名がZipで良いかは分からない。
効率とか速度とかは調べてない。問題点等あれば、指摘してほしい。

1
2
3

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
2