C# interweave two uneven List into a new List

前端 未结 4 918
别那么骄傲
别那么骄傲 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));
    
    0 讨论(0)
  • 2020-12-21 05:33

    I think you are looking for something like this:

    list1
    .SelectMany((x,idx) => new[] { x, list2[idx] })
    .Concat(list2.Skip(list1.Count));
    

    Fiddle

    0 讨论(0)
  • 2020-12-21 05:36

    If you don't need to keep the original lists intact, you can use a while loop to pop items off the front of each list:

    while(list1.Count > 0 || list2.Count > 0)
    {
        if(list1.Count > 0)
        {
            combinedList.Add(list1[0]);
            list1.RemoveAt(0);
        } 
    
        if(list2.Count > 0)
        {
            combinedList.Add(list2[0]);
            list2.RemoveAt(0);
        } 
    }
    

    Not quite as terse as Linq but easy to read and very clear what is going on.

    0 讨论(0)
  • 2020-12-21 05:52

    longer but probably more efficient

    List<string> result = new List<string>();
    using (var enumerator1 = list1.GetEnumerator())
    using (var enumerator2 = list2.GetEnumerator())
    {
        int countBefore;
        do
        {
            countBefore = result.Count;
            if (enumerator1.MoveNext())
                result.Add(enumerator1.Current);
            if (enumerator2.MoveNext())
                result.Add(enumerator2.Current);
        } while (countBefore < result.Count);
    }
    
    0 讨论(0)
提交回复
热议问题