C#中的可枚举的邮编倍数/绝对数 [英] Zip multiple/abitrary number of enumerables in C#

查看:52
本文介绍了C#中的可枚举的邮编倍数/绝对数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linq中,我们可以将两个列表与 Enumerable.Zip 方法:

In Linq we can combine two lists with a the Enumerable.Zip method:

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector
)

我想要等同于Zip的任意数量的相同类型的可枚举.方法签名有点像这样:

I would like the equivalent to Zip an arbitrary number of enumerables of the same type. Something with a method signature a bit like this:

public static IEnumerable<TResult> Zip<TIn, TResult>(IEnumerable<IEnumerable<TIn>>inputs, Func<IEnumerable<TIn>, TResult> combiner)

在迭代作为枚举的位置时,它返回一个包含来自每个对应的枚举的元素的枚举.

Where the as the enumerable is iterated, it returns an enumerable containing an element from each of the corresponding enumerables.

这存在于任何地方吗?还是使用现有的Linq方法构建起来简单?汇总多个邮编?

Does this exist anywhere? Or is it simple to build with existing Linq methods? Aggregate multiple zips?

推荐答案

由于输入是数组,因此可以创建IEnumerator<TIn>[] 然后对它们每个调用MoveNext.像这样:

Since the input is an array, you can create an IEnumerator<TIn>[] Then call MoveNext on each of them. Something like this:

IEnumerator<T>[] enumerators = inputs.Select(inp => inp.GetEnumerator()).ToArray();
int len = enumerators.Length;
while (true) {
    TResult[] result = new TResult[len];
    for(int i = 0; i < len; ++i) {
        if (!enumerators[i].MoveNext()) yield break;
        result[i] = resultSelector(enumerators[i].Current);
    }
    yield return result;
}

这篇关于C#中的可枚举的邮编倍数/绝对数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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