Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
Code Whisperer Avatar asked Oct 05 '15 23:10

Code Whisperer


People also ask

What is array example with example?

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

What is array map function?

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.

What is the map function in C?

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.

Can we use map on array?

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.


1 Answers

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)); 
like image 196
Daniel A. White Avatar answered Sep 25 '22 01:09

Daniel A. White