C# interweave two uneven List into a new List

前端 未结 4 936
别那么骄傲
别那么骄傲 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: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.

提交回复
热议问题