枚举.Zip扩展方法->如何逐个合并两个列表



类似

List<int> first = new() {11, 13, 15};
List<int> second = new() {12, 14, 16};

期望的结果是

List<int> {11, 12, 13, 14, 15, 16}

它应该通过c#中的ZipLinq查询来解决

如果我理解正确,您正在寻找firstsecond交错项,我们可以保证该first.Count == second.Count

Zip的帮助下,我们可以从firstsecond:中得到

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

相关内容

  • 没有找到相关文章

最新更新