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.
An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data[100];
Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
The map function is commonly used as a built-in Arduino C function and it's very handy in a wide range of applications. Mathematically, the mapping function is to find the corresponding value from a certain domain to another domain.
map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With