Example of array.map() in C#?

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.



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.

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));

Only for info, if people is a List<Person>, the ConvertAll method is pretty similar to JS's map, e.g:

var ages = people.ConvertAll<int>(person => person.age);

But if you have an Array and you want to use any List<T> methods, you can easily achieve that by converting your variable into a List from Array, e.g:

var ages = people.ToList().ConvertAll<int>(person => person.age);

And finally, if you really need an Array back, then you could convert it back, e.g:

var ages = people.ToList().ConvertAll<int>(person => person.age).ToArray();

But that last example is not as good as the other answers, and you should use Select if you're working only with Arrays. But if you can, I suggest you to move to List<T>, it's much better!


The LINQ extension methods on collections give you a host of really handy utilities. Select is one of them:

int[] arr = { 1, 2, 3 };
IEnumerable<string> list = arr.Select(el => el + "a");
string[] arr2 = list.ToArray();

foreach (var str in arr2)
    Console.Write(str + " ");

This should output:

1a 2a 3a

This can safely be condensed to a 1-liner:

string[] arr2 = arr.Select(el => el + "a").ToArray();

A working example:


Related docs:


Basic LINQ Query Operations (C#)


Linq's .Select is the map equivalent and .Aggregate is the fold equivalent.

var nums = new[] {1,2,3,4};
string[] r = nums.Select(x => x + "a").ToArray();

You can use the keywords from, select, in and while;
Or for your example:

 var ages = (from person in people select person.age).ToArray();

So essentially the syntax would be:

 <<list-output>> = (from <<var-name>> in <<list-input>> select <<operation>>);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.