Projects each element of a sequence into a new form.
This is a LINQ extension method for IEnumerable<TSource>.
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
IEnumerable<TResult>
An IEnumerable<TResult> whose elements are the result of invoking the transform function on each element of the source sequence.
The Select
method transforms each element in a sequence and returns a new sequence containing the transformed elements. This method does not modify the original sequence.
There are two overloads for the Select
method:
This method supports deferred execution, meaning that the transformation is not performed until the sequence is iterated over.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Transform each number into its square
IEnumerable<int> squares = numbers.Select(n => n * n);
Console.WriteLine("Squares of numbers:");
foreach (int square in squares)
{
Console.Write(square + " "); // Output: 1 4 9 16 25
}
Console.WriteLine();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<string> words = new List<string> { "apple", "banana", "cherry" };
// Transform each word into a string including its index
IEnumerable<string> indexedWords = words.Select((word, index) => $"{index}: {word}");
Console.WriteLine("Indexed words:");
foreach (string indexedWord in indexedWords)
{
Console.WriteLine(indexedWord);
// Output:
// 0: apple
// 1: banana
// 2: cherry
}
}
}