Home > Software design >  Enumerable.Zip extension method -> how to merge two list in one by one sequence
Enumerable.Zip extension method -> how to merge two list in one by one sequence

Time:07-03

like

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

desired result is

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

it solve should be by Zip Linq query in c#

CodePudding user response:

If I understand you right, you are looking for interleaving items of first and second and we can guarantee that first.Count == second.Count.

With a help of Zip we can get pairs from first and second:

{11, 13, 15} .Zip {12, 14, 16} => {{11, 12}, {13, 14}, {15, 16}}

which we can flatten with SelectMany

{{11, 12}, {13, 14}, {15, 16}} .SelectMany => {11, 12, 13, 14, 15, 16}

Code:

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

CodePudding user response:

var desire = first.Zip(second).SelectMany(x => new[] { x.First, x.Second }).ToList();
  • Related