Can I build Tuples from IEnumerables using Linq?

A more modern version updated per C# 7.0 (based on the answer of @Ani).

This uses the more readable (IMO) tuple syntax without Tuple.Create. Also note the return type and the tuple deconstruction within the Select method.

IEnumerable<(int, double, double)> TupleBuild
    (IEnumerable<double> first, IEnumerable<double> second)
    {
        return first
            .Zip(second)
            .Select((tuple, index) =>
            {
                var (fst, snd) = tuple;
                return (index, fst, snd);
            });
    }


How about with the Zip operator and the Select overload that provides the index of the element:

return first.Zip(second, Tuple.Create)
            .Select((twoTuple, index)
                      => Tuple.Create(index, twoTuple.Item1, twoTuple.Item2));

By the way, you might as well then make the method generic:

IEnumerable<Tuple<int, TFirst, TSecond>> TupleBuild<TFirst, TSecond>
(IEnumerable<TFirst> first, IEnumerable<TSecond> second) { ... }

Tags:

C#

Linq

Tuples