I've come with a solution super tricky for a simple requirement. I think I could solve the problem using LinQ, but I'm not seeing it so clearly at all. What's sure, I'm not comfortable with my code.
The requirement is the following:
Given a list of lists of string (IEnumerable>), take the first N elements from each but one by one. So given this list of list and N=10:
{aaa, bb, ccc, ddd}
{eee, fff}
{ggg, hhhhh, iii, jjj, kkk}
{lll}
{1111, 22, 333, 444, 55555, 66666}
This is the output:
{aaa, eee, ggg, lll, 111, bb, fff, hhhhh, 22, ccc}
And here is the code:
private IEnumerable<string> Extract(
IEnumerable<IEnumerable<string>> listOfList,
int N
)
{
var result = new List<string>();
for (int i = 0; i < N; i++)
{
foreach (IEnumerable<string> list in listOfList)
{
if (list.Count() > i)
{
result.Add(list.ElementAt(i));
if (result.Count >= N)
return result;
}
}
}
return result;
}
The code works, but I don't think this is maintainable nor easy to read. Thanks.
N
elements of each list, but taking the first of each, then the second of each, etc. or are you meant to take the firstN
of the sequences defined by taking the first, then the second, etc. Your code (and the example and all the answers) currently do the second, but the spec sounds like it wants the first. \$\endgroup\$