CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var abc = new List<string>{"a", "b", "c"};
var xyz = new List<string>{"x", "y", "z"};
var braidedArray = BraidArrays(new List<List<string>>{abc, xyz});
Console.WriteLine(string.Join(",", braidedArray));
// BraidArrays works for any number of arrays. Feel free to uncomment these lines to see it in action combining 3 arrays:
// var oneTwoThree = new List<string>{"1", "2", "3"};
// var braidedArrayTwo = BraidArrays(new List<List<string>>{abc, xyz, oneTwoThree});
// Console.WriteLine(string.Join(",", braidedArrayTwo));
}
private static List<T> BraidArrays<T>(List<List<T>> lists)
{
// declare our braided list we are about to build
var braided = new List<T>{};
// find the length of the longest list - project the length then call Max() to find it
var longestListLength = lists.Select(x => x.Count).Max();
// will need to loop for the longest list
for (var i = 0; i < longestListLength; i++)
{
// take the value at each index in order (if it exists)
foreach (var list in lists)
{
if (list.ElementAtOrDefault(i) != null)
{
braided.Add(list[i]);
}
}
}
// return the list!
return braided;
}
}