使用LINQ按位置组合两个列表中的条目 [英] Combine entries from two lists by position using LINQ

查看:55
本文介绍了使用LINQ按位置组合两个列表中的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个包含以下条目的列表

Say I have two lists with following entries

List<int> a = new List<int> { 1, 2, 5, 10 };
List<int> b = new List<int> { 6, 20, 3 };

我想创建另一个列表c,其中其条目是从两个列表中按位置插入的项目.因此,列表c将包含以下条目:

I want to create another List c where its entries are items inserted by position from two lists. So List c would contain the following entries:

List<int> c = {1, 6, 2, 20, 5, 3, 10}

是否有使用LINQ在.NET中做到这一点的方法?我正在查看.Zip()LINQ扩展名,但不确定在这种情况下如何使用它.

Is there a way to do it in .NET using LINQ? I was looking at .Zip() LINQ extension, but wasn't sure how to use it in this case.

提前谢谢!

推荐答案

要使用LINQ,您可以使用 LINQPad 示例代码:

To do it using LINQ, you can use this piece of LINQPad example code:

void Main()
{
    List<int> a = new List<int> { 1, 2, 5, 10 };
    List<int> b = new List<int> { 6, 20, 3 };

    var result = Enumerable.Zip(a, b, (aElement, bElement) => new[] { aElement, bElement })
        .SelectMany(ab => ab)
        .Concat(a.Skip(Math.Min(a.Count, b.Count)))
        .Concat(b.Skip(Math.Min(a.Count, b.Count)));

    result.Dump();
}

输出:

这将:

  • 将两个列表压缩在一起(当两个列表中的任何一个元素用完时将停止)
  • 产生一个包含两个元素的数组(一个来自a,另一个来自b)
  • 使用SelectMany将其展平"为一个值序列
  • 在任一列表的其余部分中串联(两次调用Concat的一个或两个都不应该添加任何元素)
  • Zip the two lists together (which will stop when either runs out of elements)
  • Producing an array containing the two elements (one from a, another from b)
  • Using SelectMany to "flatten" this out to one sequence of values
  • Concatenate in the remainder from either list (only one or neither of the two calls to Concat should add any elements)

现在,话虽如此,我个人将使用此功能:

Now, having said that, personally I would've used this:

public static IEnumerable<T> Intertwine<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
    using (var enumerator1 = a.GetEnumerator())
    using (var enumerator2 = b.GetEnumerator())
    {
        bool more1 = enumerator1.MoveNext();
        bool more2 = enumerator2.MoveNext();

        while (more1 && more2)
        {
            yield return enumerator1.Current;
            yield return enumerator2.Current;

            more1 = enumerator1.MoveNext();
            more2 = enumerator2.MoveNext();
        }

        while (more1)
        {
            yield return enumerator1.Current;
            more1 = enumerator1.MoveNext();
        }

        while (more2)
        {
            yield return enumerator2.Current;
            more2 = enumerator2.MoveNext();
        }
    }
}

原因:

  • 它不会多次枚举ab
  • 我对Skip
  • 的表现持怀疑态度
  • 它可以与任何IEnumerable<T>一起使用,而不仅限于List<T>
  • It doesn't enumerate a nor b more than once
  • I'm skeptical about the performance of Skip
  • It can work with any IEnumerable<T> and not just List<T>

这篇关于使用LINQ按位置组合两个列表中的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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