Antoine
Antoine

Reputation: 1812

Combining two lists with C#

In OCaml, there's a function which takes two lists of the same size and returns a list of tuples:

val combine : 'a list -> 'b list -> ('a * 'b) list

Is there something similar in C#?

I don't I have strong requirements about the output's type. It can be a list of tuples, or something like a dictionary.

Upvotes: 2

Views: 172

Answers (1)

dcastro
dcastro

Reputation: 68660

There is the Enumerable.Zip extension method. The second argument tells the method what to do with each pair of elements.

IEnumerable<Tuple<int, int>> pairs = a.Zip(b, Tuple.Create);

IEnumerable<int> sums = a.Zip(b, (x, y) => x + y);

If one collection is larger than the other, the remaining elements of the larger collection will be ignored.

Upvotes: 7

Related Questions