3

I have some types S and T (e.g. S=object and T=string). I have a pair of arrays of these types, i.e.

(S[], T[]) pairOfArrays;

and I want to convert it to an array of pairs, i.e.

(S, T)[] arrayOfPairs;

How do I do that? I am most interested in solutions with LINQ, if possible. Please assume that the two arrays in pairOfArrays have the same length.


I know the other direction:

pairOfArrays = (arrayOfPairs.Select(i => i.Item1).ToArray(),
                arrayOfPairs.Select(i => i.Item2).ToArray());

The problem I have with the sought direction is: in order to iterate (use Select and such) I need an IEnumerable, but (S[], T[]) is no IEnumerable. And if I start with pairOfArrays.Item1.Select(..., then I don't know how to get to the same entry (index-wise) of Item2 as I currently have inside my Select statement.

Kjara
  • 2,504
  • 15
  • 42

2 Answers2

5

Using Zip, you can get the corresponding elements and transform them into Tuples:

var arrayOfPairs = pairOfArrays.Item1.Zip(pairOfArrays.Item2, (f, s) => new Tuple<S, string>(f, s))
                               .ToArray();

or as of C#7:

var arrayOfPairs = pairOfArrays.Item1.Zip(pairOfArrays.Item2, (f, s) => (f, s))
                               .ToArray();

a less idiomatic approach than the above but still a good solution would be using Enumerable.Range:

var arrayOfPairs = 
    Enumerable.Range(0, pairOfArrays.Item1.Length)
            .Select(index => (pairOfArrays.Item1[index], pairOfArrays.Item2[index]))
            .ToArray();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
3

You can use Zip for this:

var result = arrayOfS.Zip(arrayOfT, (first, second) => new { S = first, T = second });

which results in a list of { S, T }.

Alternativly a good old-style loop:

for(int i = 0; i < arrayOfS.Length; i++)
{
    result[i] = new ST(arrayOfS[i], arrayOfT[i]);
}

However this way you can´t use anonymous types.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111