加入两个不同长度的列表

spi*_*iry 9 c# linq

我正在使用LINQ:

List<String> listA = new List<string>{"a", "b", "c", "d", "e", "f", "g"};  
List<String> listB = new List<string>{"1", "2", "3"};  
Run Code Online (Sandbox Code Playgroud)

期望的结果:

{"a", "1", "b", "2", "c", "3", "d", "1", "e", "2", "f", "3", "g", "1"}  
Run Code Online (Sandbox Code Playgroud)

我试过但失败了:

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"}  
Run Code Online (Sandbox Code Playgroud)

我怎么能用LINQ做到这一点?

gof*_*al3 9

这是有效的,即使我不确定为什么你需要它作为linq表达式:

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);
Run Code Online (Sandbox Code Playgroud)

  • 这是迄今为止唯一可行的linq方法+1你可以将它缩短为`var mix = Enumerable.Range(0,Math.Max(listA.Count,listB.Count)).SelectMany(i => new [] {listA [i%listA.Count],listB [i%listB.Count]});` (4认同)