Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can combine two enumerations with a custom function?

Given are two IEnumerable<A> a and IEnumerable<B> b. It is guaranteed that they are of the same length. I would like to create a new IEnumerable<C> c in which each item c_i is derived using a Func<A, B, C> f by c_i := f (a_i, b_i).

The best I could come up with is manual simultaneous enumeration over both sources and yield-ing the current result, implemented as an extension method. Is there a short way to do it without custom code in .NET >= 4.0?

like image 261
mafu Avatar asked Jun 09 '26 14:06

mafu


2 Answers

You can use Enumerable.Zip.

e.g.

var c = a.Zip(b, (a, b) => SomeFunc(a, b));
like image 155
Dustin Kingen Avatar answered Jun 11 '26 02:06

Dustin Kingen


Use Zip method.

http://msdn.microsoft.com/en-us/library/dd267698.aspx

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

    int[] numbers = { 1, 2, 3, 4 };
    string[] words = { "one", "two", "three" };

    var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

    foreach (var item in numbersAndWords)
        Console.WriteLine(item);

    // This code produces the following output: 

    // 1 one 
    // 2 two 
    // 3 three
like image 42
Jakub Konecki Avatar answered Jun 11 '26 04:06

Jakub Konecki