139

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.

2
  • 3
    (new[]{1,2,3,4}).Select(v => String.Format("{0}a", v)) Commented Oct 5, 2015 at 23:35
  • 2
    @AlexeiLevenkov You missed the .ToArray() on the end. Commented Oct 6, 2015 at 1:47

6 Answers 6

201

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));
Sign up to request clarification or add additional context in comments.

2 Comments

on c#6 : var items = Enumerable.Range(1, 4).Select(num => string.Format($"{num}a"));
@BartCalixto - you don't need the string.Format... var items = Enumerable.Range(1, 4).Select(num => $"{num}a");
33

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!

1 Comment

convert to List and use ConvertAll allow me to refactor my large Select code that is not allow to have parameter constructor in Linq
5

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

1 Comment

How this is different from @Richard Schneider's answer. Also what's the need to do ToList()??
5

If you don't want to perform conversion to/from an array Array.ConvertAll can to the work. It is declared in Array class of System namespace (remember to add using System; at the top of the file) as:

public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, Converter<TInput,TOutput> converter);

Example:

var items = new[] {"abc", "ab", "abcde"};

var result = Array.ConvertAll(items, p => p.Length);
            
Console.Out.WriteLine(string.Join(", ", result)); // Outputs 3, 2, 5

Method reference: https://learn.microsoft.com/en-us/dotnet/api/system.array.convertall?view=net-5.0

Check this section to see .NET version compatibility: https://learn.microsoft.com/en-us/dotnet/api/system.array.convertall?view=net-5.0#applies-to

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.