Select
Learn to transform each element with Select.
Transforming with Select
The Select method transforms each element of a collection. It takes a lambda and produces a new value for each element. The result is a new collection of transformed elements; the original is unchanged.
Example: numbers.Select(n => n * n) squares each number. words.Select(w => w.ToUpper()) uppercases each word. Select is the C# equivalent of the map operation and is used to reshape data.
Chaining Where and Select
You can chain LINQ methods: apply one method to the result of another. Order matters: first filter with Where, then transform with Select. numbers.Where(n => n > 2).Select(n => n * 10) first keeps numbers greater than 2, then multiplies each by 10.
Chaining builds a readable pipeline. Each method returns an IEnumerable<T>; the next method applies to that. End with .ToList() or a foreach loop.
Exercise Compute squares and print
Compute the square of each number in numbers with Select and print each in a foreach loop. Square: n * n.
Show example solution
Generate squares with numbers.Select(n => n * n), loop with foreach, print with Console.WriteLine(s).
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 2, 3, 4 };
foreach (var s in numbers.Select(n => n * n))
{
Console.WriteLine(s);
}
}
}
Test yourself
-
Match Select to its result
- Select(n => n * 2)
- Double
- Select(n => n * n)
- Square
- Select(w => w.ToUpper())
- UPPERCASE
- Select(s => s.Length)
- Length
-
Complete the Select body
var squares = numbers.Select(n => n ____ n);Show answer
var squares = numbers.Select(n => n * n); -
What does Select return?
var r = words.Select(w => w.Length);- IEnumerable<int>
- IEnumerable<string>
- int
- string
Show answer
IEnumerable<int> — Correct. Select produces a new collection typed by the lambda's return value; Length is int, so it returns IEnumerable<int>.