C # weaves two uneven lists into a new list

I have two lists, both from different lengths. What I'm trying to achieve is a third list containing the first item from list1, then the first item from list2, then the second item from list1 and the second item from list2, etc. Until one of the two is exhausted (they are "uneven"), and then just add all the remaining items from this list.

the result should have the same number of elements as list1 and list2.

I cannot use something like Union.ToList (), since this does not interweave the two, it just adds all the elements from the list1 example to the end of list2 and displays it as a result. I tried .Zip (Linq), however, it looks like they take in two elements and combine them into one element (namely, concatenating two strings into one long string).

List<string> list1 = new List<string>(){
            "4041",
            "4040"              
        };

List<string> list2 = new List<string>(){ 
            "4039",
            "4044", 
            "4075", 
            "4010",
            "4100",
            "4070", 
            "4072" 
        };


// Ideal result:    
result = { "4041",
      "4039",
      "4040"  
      "4044",      
      "4075", 
      "4010",
      "4100",
      "4070", 
      "4072" 
}; 
+4
source share
4 answers
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));
+5
source

If you don't need to keep the original lists intact, you can use the while loop to mark items in 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 accurate, like Linq, but easy to read and very clear what is happening.

+3
source

, , ,

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);
}
+1

, - :

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

Fiddle

0

Source: https://habr.com/ru/post/1548183/


All Articles