gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:14:54 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com