Example of array.map() in C#?
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:
https://ideone.com/mxxvfy
Related docs:
Enumerable.Select
Basic LINQ Query Operations (C#)
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!
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));