Example of array.map() in C#?

Code Whisperer picture Code Whisperer · Oct 6, 2015 · Viewed 80.1k times · Source

Consider the following common JavaScript construct

var ages = people.map(person => person.age);

Giving the desired result, which is an array of ages.

What is the equivalent of this in C#? Please include a simple example. The documentation indicates select or possible selectAll but I can't find an example online or any other SO question which can be pasted in and works.

If possible, give an example which turns the following array {1,2,3,4} into the following {'1a','2a','3a','4a'}. For each element, append "a" to the end, turning it from an Integer to a String.

Answer

Daniel A. White picture Daniel A. White · Oct 6, 2015

This is called projection which is called Select in LINQ. That does not return a new array (like how JavaScript's .map does), but an IEnumerable<T>. You can convert it to an array with .ToArray.

using System.Linq; // Make 'Select' extension available
...
var ages = people.Select(person => person.Age).ToArray();

Select works with all IEnumerable<T> which arrays implement. You just need .NET 3.5 and a using System.Linq; statement.

For your 2nd example use something like this. Notice there are no arrays in use - only sequences.

 var items = Enumerable.Range(1, 4).Select(num => string.Format("{0}a", num));