What is the equivalent of PHP array_map in C #?

4

In PHP , I can create a new array based on an existing array , using the array_map function.

With it, I can define a callback that is responsible for the settings of each value that will be used to create this "new array ".

Example in PHP:

 $numeros = [1, 2, 3];

 $numeros_dobrados = array_map(function ($value)
 {
        return $value * 2;
 }, $numeros);


print_r($numeros); // [2, 4, 6]

I also know you can do this in python .

Example in Python:

 [x * 2 for x in range(1, 10) ]

 > [2, 4, 6, 8, 10, 12, 14, 16, 18]

How could I do this with this array in C #?

C # example:

  var arr = new int[] {1, 2, 3}
    
asked by anonymous 27.04.2016 / 17:34

1 answer

6
using System.Linq;

var arr = Enumerable.Range(1, 3).Select(x => x * 2).ToArray();

Here is the implementation of Enumerable.Range :

public static IEnumerable<int> Range(int start, int count) {
    long max = ((long)start) + count - 1;
    if (count < 0 || max > Int32.MaxValue) throw Error.ArgumentOutOfRange("count");
    return RangeIterator(start, count);
}

static IEnumerable<int> RangeIterator(int start, int count) {
    for (int i = 0; i < count; i++) yield return start + i;
}

If you want to understand a little more about how the methods work, since they use Lazy Evaluation (you can notice by the keyword yield ), here is a link for reference :

How useful is the word "yield" ?

    
27.04.2016 / 17:48