c# - 使用 LINQ 按位置组合两个列表中的条目

标签 c# .net linq

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

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

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

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

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

提前致谢!

最佳答案

要使用 LINQ 执行此操作,您可以使用 LINQPad 的这一部分示例代码:

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();
}

输出:

LINQPad example output

这将:

  • 将两个列表压缩在一起(当元素用完时将停止)
  • 生成一个包含两个元素的数组(一个来自 a,另一个来自 b)
  • 使用 SelectMany将其“扁平化”为一个值序列
  • 连接任一列表的剩余部分(只有一个或两个调用 Concat 都不应添加任何元素)

现在,话虽如此,我个人会使用这个:

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();
        }
    }
}

原因:

  • 它不枚举a也不b不止一次
  • 我对 Skip 的表现持怀疑态度
  • 它可以与任何 IEnumerable<T> 一起使用而不仅仅是 List<T>

关于c# - 使用 LINQ 按位置组合两个列表中的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222046/

相关文章:

c# - 如何在Web服务器上获取用户的IP地址?

.net - 使用.NET 中注册的 com 对象 dll

.net - 如何确保连接字符串用于本地计算机

c# - for(或)foreach循环和linq查询在速度的情况下有什么区别

c# - 通过 MEF 在 plugin2 中使用 plugin1 中可用的方法

c# - WebAPI PushStreamContent 远程主机关闭连接

c# - C# .NET 标签中的多种颜色

c# - Linq Navigation Properties complex where ID in (select id from...)

c# - 使用linq从基类列表中获取相同类型的继承类项

c# - 我如何告诉我的控制台应用程序在我输入数字之前不要继续?