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
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));
I think you are looking for something like this:
list1
.SelectMany((x,idx) => new[] { x, list2[idx] })
.Concat(list2.Skip(list1.Count));
Fiddle
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.
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);
}