3

I've got 3 IEnumerables of integers and I would like to make an array of Tuple out of it. What's the best approach? If I had just 2 IEnumerables I would use Zip but in this case?

darenn
  • 469
  • 5
  • 17
  • See duplicate. `var result = i1.Concat(i2).Concat(i3);`. If this doesn't answer your question, show a small code example of what you currently have and explain what you'd like to accomplish. – CodeCaster Jul 04 '14 at 10:52
  • That's not the same problem – Dennis_E Jul 04 '14 at 10:54
  • 1
    @CodeCaster I think he wants the result to be of type `IEnumerable>` – Matthew Mcveigh Jul 04 '14 at 10:54
  • @Matthew that's exactly what I want – darenn Jul 04 '14 at 10:55
  • 1
    Since answers are closed: take a look at the Zip method and you can easily adjust it for 3 enumerables http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs – Dennis_E Jul 04 '14 at 10:56
  • @darenn If the previous comment describes your problem than name your question like: Combining items into tuples from multiple(>2) IEnumerables in parallel by one. It is an awful title, but I am unable to think of any better one. – Eugene Podskal Jul 04 '14 at 10:57
  • 1
    In that case see [How to combine more than two generic lists in C# Zip?](http://stackoverflow.com/questions/10297124/how-to-combine-more-than-two-generic-lists-in-c-sharp-zip). – CodeCaster Jul 04 '14 at 10:59
  • But what about the arbitrary number of IEnumerables? Zipping the zipped multiple times is not the cleanest solution. – Eugene Podskal Jul 04 '14 at 11:02

2 Answers2

10

This is a scenario where it is easiest to use the iterator directly, rather than foreach:

using(var i1 = seq1.GetEnumerator())
using(var i2 = seq2.GetEnumerator())
using(var i3 = seq3.GetEnumerator())
{
    while(i1.MoveNext() && i2.MoveNext() && i3.MoveNext())
    {
        var tuple = Tuple.Create(i1.Current, i2.Current, i3.Current);
        // ...
    }
}

The // ... here could be:

  • yield return tuple
  • someList.Add(tuple);
  • or the actual thing you want to do
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

It is possible (though maybe not the best performant solution) to Zip twice, as in:

var result = seq1.Zip(seq2, Tuple.Create)
    .Zip(seq3, (t2, z) => Tuple.Create(t2.Item1, t2.Item2, z));
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181