交织多个(2个以上)使用LINQ不规则名单 [英] Interleaving multiple (more than 2) irregular lists using LINQ

查看:128
本文介绍了交织多个(2个以上)使用LINQ不规则名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下数据

IEnumerable<IEnumerable<int>> items = new IEnumerable<int>[] { 
    new int[] { 1, 2, 3, 4 },
    new int[] { 5, 6 },
    new int[] { 7, 8, 9 }
};



什么是返回与交错,所以我会得到物品的平面列表的最简单方法结果

What would be the easiest way to return a flat list with the items interleaved so I'd get the result:

1,5,7,第2,第6,第8,3,9,4

1, 5, 7, 2, 6, 8, 3, 9, 4

注:内列出的数量在运行时不会知

Note: The number of inner lists is not known at runtime.

推荐答案

什么你所描述的,实质上是一个的Transpose方法的,其中包含的悬垂件,结果是扁平。这里是我的尝试:

What you're describing is essentially a Transpose Method where overhanging items are included and the result is flattened. Here's my attempt:

static IEnumerable<IEnumerable<T>> TransposeOverhanging<T>(
    this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
    try
    {
        T[] g;
        do
        {
            yield return g = enumerators
                .Where(e => e.MoveNext()).Select(e => e.Current).ToArray();
        }
        while (g.Any());
    }
    finally
    {
        Array.ForEach(enumerators, e => e.Dispose());
    }
}

例如:

Example:

var result = items.TransposeOverhanging().SelectMany(g => g).ToList();
// result == { 1, 5, 7, 2, 6, 8, 3, 9, 4 }

这篇关于交织多个(2个以上)使用LINQ不规则名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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