0

I've two lists like this:

a1, a2, a3, ..

and

b1, b2, b3, ..

How can I mix them to have a result like this?:

a1, b1, a2, b2, ..


I thought of this, but I don't like it:

for (int i = 0; i < List1.Count; i++)
{
    FinalList.Add(List1[i]));

    if (i < List2.Count)
        FinalList.Add(List2[i]));
}

if (List1.Count < List2.Count)
{
    for (int i = List1.Count; i < List2.Count; i++)
    {
        FinalList.Add(List2[i]);
    }
}
Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Blendester
  • 1,583
  • 4
  • 19
  • 43

2 Answers2

2

You can zip matching part of two sequences and then concat rest of the longest sequence:

var FinalList = List1.Zip(List2, (a,b) => new [] { a, b })
   .SelectMany(x => x)
   .Concat(List1.Count < List2.Count ? List2.Skip(List1.Count) : List1.Skip(List2.Count))
   .ToList();

If you want something more effective, then you can write your own extension method

public static IEnumerable<T> Merge<T>(this IEnumerable<T> source1, IEnumerable<T> source2)
{
    // null-check here
    using(var enumerator1 = source1.GetEnumerator())
    using(var enumerator2 = source2.GetEnumerator())
    {
        bool hasItem1, hasItem2;

        do
        {
            if (hasItem1 = enumerator1.MoveNext()) yield return enumerator1.Current;
            if (hasItem2 = enumerator2.MoveNext()) yield return enumerator2.Current;
        }
        while (hasItem1 || hasItem2);
    }
}

Usage:

var finalList = List1.Merge(List2).ToList();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

This works for me:

var List1 = new [] { "a1", "a2", "a3" };
var List2 = new [] { "b1", "b2", "b3" };

var mix =   
    List1
        .Zip(List2, (l1, l2) => new [] { l1, l2 })
        .SelectMany(x => x);

It gives:

a1 
b1 
a2 
b2 
a3 
b3 
Enigmativity
  • 113,464
  • 11
  • 89
  • 172