Join two lists of different length

  • A+
Category:Languages

I am using LINQ:

List<String> listA = new List<string>{"a", "b", "c", "d", "e", "f", "g"};   List<String> listB = new List<string>{"1", "2", "3"};   

Desired result:

{"a", "1", "b", "2", "c", "3", "d", "1", "e", "2", "f", "3", "g", "1"}   

I tried but fail:

var mix = ListA.Zip(ListB, (l1, l2) => new[] { l1, l2 }).SelectMany(x => x);   //Result : {"a", "1", "b", "2", "c", "3"}    var mix = ListA.Zip(ListB, (a, b) => new[] { a, b })         .SelectMany(x => x)         .Concat(ListA.Count() < ListB.Count() ? ListB.Skip(ListA.Count()) : ListA.Skip(ListB.Count()))         .ToList();   //Result : {"a", "1", "b", "2", "c", "3", "d", "e", "f", "g"}   

How can I do this using LINQ?

 


This works, even if I am not sure why you need it as linq expression:

var mix = Enumerable            .Range(0, Math.Max(listA.Count, listB.Count))            .Select(i => new[] { listA[i % listA.Count], listB[i % listB.Count] })            .SelectMany(x => x); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: