1

I want to create an enumerator which will iterate over multiple lists elements one-by-one returning a list of them. For example let's say we have 3 lists, the enumerator will first yield the elements at index 0 then elements at index one and so on..

So far I have the code below but it does not work and returns only the first element. How can I achieve this ? Is this even possible ?

private class Merger : IEnumerable
{
    private readonly List<List<string>> paths;

    private readonly int maxPathLength;

    public Merger(List<List<string>> paths)
    {
        this.paths = paths;

        maxPathLength = paths.Max(x => x.Count);
    }

    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < maxPathLength; i++)
        {
            yield return paths.Select(x => x[i]);
        }
    }

}
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • Actually, I don't think @Heinzi is correct referencing "How to “zip” or “rotate” a variable number of lists?" as a duplicate of the current Cemre's question. Cemre, an answer to your question is much simpler. You have to change just one line in your code: yield return paths.ElementAt(i); - instead of paths.Select(...) – Arkady Yampolsky Dec 14 '14 at 22:13
  • @ArkadyYampolsky: How are the two problems different? If the line mentioned by you is changed (and `Max` is replaced by `Min`, lest you get an ArgumentOutOfRangeException on ElementAt), you get exactly the algorithm mentioned in the duplicate (question part, not the answers). – Heinzi Dec 15 '14 at 05:58
  • Oh, yes @Heinzi, I forgot to write that another line had to be changed also: `for (int i = 0; i < paths.Count; i++)`. I have no idea why Cemre needs `maxPathLength` – Arkady Yampolsky Dec 15 '14 at 06:47
  • @ArkadyYampolsky: Careful, that needs to be `i < minPathLength`, not `paths.Count`! `paths.Count` returns the number of paths, but the loop need the number of *elements* in the paths. – Heinzi Dec 15 '14 at 08:22

0 Answers0