交错合并使用LINQ? [英] Interleaved merge with LINQ?

查看:119
本文介绍了交错合并使用LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在尝试了一下使用LINQ。比方说,我有相同长度的两个集合:

I'm currently experimenting a bit with LINQ. Let's say I have two collections of identical length:

var first = new string[] { "1", "2", "3" };
var second = new string[] { "a", "b", "c" };



我想这两个集合合并成一个,而是以交错的方式。由此得到的顺序应该是:

I would like to merge those two collections into one, but in an interleaved fashion. The resulting sequence should thus be:

"1", "a", "2", "b", "3", "c"

我想出来的,到目前为止是结合邮编,一个匿名类型和的SelectMany

What I've come up with so far is a combination of Zip, an anonymous type and SelectMany:

var result = first.Zip( second, ( f, s ) => new { F = f, S = s } )
                  .SelectMany( fs => new string[] { fs.F, fs.S } );



有谁知道的替代/简单的方式实现与LINQ这种交错的合并?

Does anybody know of an alternate/simpler way to achieve such an interleaved merge with LINQ?

推荐答案

警告:这将跳过尾随元素;如果枚举有不同的长度。如果您想要在空替代垫出较短的收集,使用安德鲁谢泼德的答案下方。

Warning: this will skip trailing elements if the enumerations have different lengths. If you'd rather substitute in nulls to pad out the shorter collection, use Andrew Shepherd's answer below.

您可以编写自己的交错扩展方法,像这个例子的。

You could write your own Interleave extension method, like in this example.

internal static IEnumerable<T> InterleaveEnumerationsOfEqualLength<T>(
    this IEnumerable<T> first, 
    IEnumerable<T> second)
{
    using (IEnumerator<T>
        enumerator1 = first.GetEnumerator(),
        enumerator2 = second.GetEnumerator())
    {
        while (enumerator1.MoveNext() && enumerator2.MoveNext())
        {
            yield return enumerator1.Current;
            yield return enumerator2.Current;
        }
    }
}

这篇关于交错合并使用LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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