I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:
List A
object a1
object a2
You could use the Enumerable.Zip() method in System.Linq.
IEnumerable> pairs = listA.Zip(listB, (a, b) => Tuple.Create(a, b));
Example using this resultant enumerable:
foreach (Tuple pair in pairs)
{
A a = pair.Item1;
B b = pair.Item2;
}
Shame there's not an overload that automates the tupleation in .NET. Such an extension would look like this:
public static IEnumerable> Zip(this IEnumerable first, IEnumerable second)
{
return first.Zip(second, Tuple.Create);
}
Which would mean you could then write code that looks like:
IEnumerable> pairs = listA.Zip(listB);
Note: Another option would be to create anonymous types instead of Tuple but the downside to this approach is that you would not be able to (usefully) pass the resultant IEnumerable out of the method it is created in owing to the type not having a name.