What is the equivalent of the PHP array_map in C#?

Asked

Viewed 92 times

5

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

With it, I can define a callback that is responsible for the definitions of each value that will be used in creating 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 that you can do this in python.

Python example:

 [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#?

Example in C#:

  var arr = new int[] {1, 2, 3}

1 answer

7


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 methods work, since they use Lazy Evaluation (you may notice by the word reserved Yield, here is a link to reference:

What is the use of the reserved word "Yield"?

  • Just so I understand: Enumerable is a class, and Range is a static method? Because there was no instance... Or Enumerable is the namespace and Range is the class?

  • Enumerable is a static class that allows you to use a static method that returns a Ienumerable<int>. The advantage of Enumerable.Range is that by using Ienumerable it allows you to use Lazy Evaluation, which is very useful in some scenarios.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.