假设我有两个包含以下条目的列表
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();
}
输出:
这将:
- 将两个列表压缩在一起(当元素用完时将停止)
- 生成一个包含两个元素的数组(一个来自 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/