0

I have 2 sequences:

l1 = { "a1", "a2"}

l2 = { "b1", "b2"}

I want to return a third sequence:

l3 = { new A {a = "a1", b = "b1"}, new A {a = "a2", b = "b2"}}}

How can I use linq to do so?

1
  • Do you have something to show or just expect us to write the code?
    – L.B
    Mar 14, 2012 at 22:39

3 Answers 3

4

You are looking for the Zip API

var l3 = l1.Zip(l2, (left, right) => new A { a = left, b = right });

Note: This wasn't added to the .Net Framework until 4.0. It's fairly easy to code up a 3.5 version though if that's what you're using.

1
3

You're looking for the zip operation from functional programming, which takes corresponding elements from two sequences and builds a third sequence containing the matching pairs. In C#, this is implemented using Enumerable.Zip. You can get the specific result you are looking for with

Enumerable.Zip(l1, l2, (elem1, elem2) => new A {a = elem1, b = elem2});
1

Assuming you have a class A and both sequences have the same number of elements in the same order:

var l1 = new [] { "a1", "a2"};
var l2 = new [] { "b1", "b2"};

var l3 = l1.Zip(l2, (x,y) => new { A { a = x, b = y });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.