I seem to be a bit stuck on this, but my experience in Linq is not great. Basically, I have something like this code:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
public class B
{
public List<Point> Points { get; set; }
public B(IEnumerable<int> Xs, IEnumerable<int> Ys)
{
// How to best combine Xs and Ys into Points ?
}
}
Now, how do I fill in that constructor to properly join up those collections? I would normally use a .Join(), but there is no inner key to join on. It should also be able to handle the off-chance that one array has fewer elements than the other or is empty (should never occur, but it’s possible).
In C# 4 you can use the Zip operator:
In C# 3, you can use
ElementAton one of the sequences with select to do the same thing:The main problem with the second option is that
ElementAtmay be very expensive if theIEnumerablecollection 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: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:
If you’re using
Zip(), you automatically end up with the second options, as the documentation indicates:The final step of all of this, is that you need to convert the projects result into a list to assign it to your
Pointsobject. That part is easy, use theToList()method:or in C# 4: