类似
List<int> first = new() {11, 13, 15};
List<int> second = new() {12, 14, 16};
期望的结果是
List<int> {11, 12, 13, 14, 15, 16}
它应该通过c#中的Zip
Linq查询来解决
如果我理解正确,您正在寻找first
和second
的交错项,我们可以保证该first.Count == second.Count
。
在Zip
的帮助下,我们可以从first
和second
:中得到对
{11, 13, 15} .Zip {12, 14, 16} => {{11, 12}, {13, 14}, {15, 16}}
我们可以用SelectMany
来压平
{{11, 12}, {13, 14}, {15, 16}} .SelectMany => {11, 12, 13, 14, 15, 16}
代码:
List<int> first = new() { 11, 13, 15 };
List<int> second = new() { 12, 14, 16 };
var result = first
.Zip(second, (f, s) => new int[] { f, s })
.SelectMany(array => array)
.ToList();
var desire = first.Zip(second).SelectMany(x => new[] { x.First, x.Second }).ToList();