In C# 4 you can use the Zip operator:
var result = Xs.Zip( Ys, (a,b) => new Point(a,b) );
In C# 3, you can use ElementAt
on one of the sequences with select to do the same thing:
var result = Xs.Select( (x,i) => new Point( x, Ys.ElementAt(i) );
The main problem with the second option is that ElementAt
may be very expensive if the IEnumerable
collection is itself a projection (as opposed to something that implements native indexing operations, like an array or List). You can get around that by first forcing the second collection to be a list:
var YsAsList = Ys.ToList();
var result = Xs.Select( (x,i) => new Point( x, YsAsList.ElementAt(i) );
Another issue you have to deal with (if you're not using Zip) is how to handle unbalanced collections. If one sequence is longer than the other you have to decide what the correct resolution should be. Your options are:
- Don't support it. Fail or abort the attempt.
- Zip as many items as exist in the shorter sequence.
- Zip as many items as exist in the longer sequence, substituting default values for the short sequence.
If you're using Zip()
, you automatically end up with the second options, as the documentation indicates:
The method merges each element of the first sequence with an element
that has the same index in the second
sequence. If the sequences do not have
the same number of elements, the
method merges sequences until it
reaches the end of one of them. For
example, if one sequence has three
elements and the other one has four,
the result sequence will have only
three elements.
The final step of all of this, is that you need to convert the projects result into a list to assign it to your Points
object. That part is easy, use the ToList()
method:
Points = Xs.Select( (x,i) => new Point( x, Ys.ElementAt(i) ).ToList();
or in C# 4:
Points = Xs.Zip( Ys, (a,b) => new Point(a,b) ).ToList();