C# interweave two uneven List into a new List

前端 未结 4 928
别那么骄傲
别那么骄傲 2020-12-21 04:52

I have two List, both of different lengths. What I am trying to achieve is a third List that contains the first element from list1, then the first element from list2, then s

4条回答
  •  醉话见心
    2020-12-21 05:27

    int length = Math.Min(list1.Count, list2.Count);
    
    // Combine the first 'length' elements from both lists into pairs
    list1.Take(length)
    .Zip(list2.Take(length), (a, b) => new int[] { a, b })
    // Flatten out the pairs
    .SelectMany(array => array)
    // Concatenate the remaining elements in the lists)
    .Concat(list1.Skip(length))
    .Concat(list2.Skip(length));
    

提交回复
热议问题