Given that there I have a list of lists, List, in which all lists contain 0 or more items, likely, but not necessarily all the same number. And I would like tho have a list containing all the items in the Lists... but I want the order to be as follows: first the first items off all the lists, in order that they appear in the 'super-list'.<List<T>>
Ex.
List[0] = { 'Apple', 'Blueberry', 'Cranberry' }
List[1] = { 'Anteater', 'Baboon', 'Camel', 'Dodo'}
List[2] = { 'Albatross', 'Blackbird', 'Chicken'}
result = { 'Apple', 'Anteater', 'Albatross', 'Blueberry', 'Baboon',
'Blackbird', 'Cranberry', 'Camel', 'Chicken', 'Dodo' }
(note that this is NOT alphabetical order, Blueberry comes before Baboon)
Ofcourse, i could just loop through the 'superlist' with a counter, adding items to the resultslist one by one, as long as there is a list that isn't empty:
int i = 0;
bool done = false;
while (!done)
{
bool found = false;
foreach (list l in superlist)
{
if (l.Count() > i)
{
found = true;
result.Add(l[i]);
}
}
i++;
if (!found)
done = true;
}
But it would be way nicer to use some optimized LINQ function to do this. I have been looking into Zip, GroupBy and Aggregate, but couldn't get them to work.
So: Is there a pretty LINQ function, or combination of multiple, that would turn this into pretty code, or should I stick by (and maybe optimize) my current function?
Edit: A simple SelectMany(x => x) also doesn't do the trick, as it preserves the order of the lists, instead of folding them, like my algorithm does. See my initial question for more details.