Home > front end >  C# Select equivalent of javascript map
C# Select equivalent of javascript map

Time:03-25

Just trying to see if C# select has the same capabilities like javascript map or not (doing some computations and then returning at the end).

For example:

const numberList = [1,2,3,4,5];
const newNumberList = numberList.map(number => {
  const modifiedNumber = number * 2;
  return modifiedNumber;
})

Yes, in this example, I can just do number => number * 2. But I am wondering for more complex scenarios where I need to do some function calls to figure out some values and then make use of them and return a list at the end.

CodePudding user response:

You've got three options, one of which you've already pointed out.

One - single statement lambda

int[] numbers = { 1, 2, 3, 4, 5 };
int[] newNumbers = numbers.Select(x => x * 2).ToArray();

Two - multi-statement lambda

int[] newNumbers = numbers
    .Select(x => {
        var newVal = x * 2;
        return newVal;
    })
    .ToArray();

Three - use an actual method (rather than anonymous method)

private static int MultByTwo(int val)
{
    return val * 2;
}

// ...

int[] newNumbers = numbers.Select(MultByTwo).ToArray();

Note, you don't write MultByTwo(), it's just the name of the method.

CodePudding user response:

Yes, Select is the equivalent of map. Indeed, LINQ is a functional interface over IEnumerable<T> just like the JS implementation on arrays. The signature is:

IEnumerable<T> => (T => R) => IEnumerable<R>

As long as you adhere to the Select contract you can write more complex code that calls functions that call other functions and so on.

  • Related