Method `Select`

Namespace: System.Linq
Assembly: System.Linq.dll

Projects a selector function onto each element of a sequence.

Syntax

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)

Parameters

source
Type: IEnumerable<TSource>
An IEnumerable<TSource> whose elements to project.
selector
Type: Func<TSource, TResult>
A transform function to apply to each element.

Return Value

Type: IEnumerable<TResult>
An IEnumerable<TResult> whose elements are the result of invoking the transform function on each element of the source sequence.

Exceptions

ArgumentNullException
source is null.
-or-
selector is null.

Remarks

The Select extension method enables you to transform each element in a sequence into a new form. It takes a function that is applied to every element, and the result of this function becomes the element in the output sequence. This is a fundamental operation in LINQ for data transformation.

Examples

C#
Visual Basic
using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main()
    {
        List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };

        // Square each number in the list
        IEnumerable<int> squaredNumbers = numbers.Select(n => n * n);

        Console.WriteLine("Squared numbers:");
        foreach (var num in squaredNumbers)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();

        // Create a list of strings representing the numbers
        IEnumerable<string> stringNumbers = numbers.Select(n => "Number: " + n);

        Console.WriteLine("\nString representation of numbers:");
        foreach (var s in stringNumbers)
        {
            Console.WriteLine(s);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class Example
    Public Shared Sub Main()
        Dim numbers As New List(Of Integer)() From {1, 2, 3, 4, 5}

        ' Square each number in the list
        Dim squaredNumbers As IEnumerable(Of Integer) = numbers.Select(Function(n) n * n)

        Console.WriteLine("Squared numbers:")
        For Each num In squaredNumbers
            Console.Write(num & " ")
        Next
        Console.WriteLine()

        ' Create a list of strings representing the numbers
        Dim stringNumbers As IEnumerable(Of String) = numbers.Select(Function(n) "Number: " & n)

        Console.WriteLine(vbCrLf & "String representation of numbers:")
        For Each s In stringNumbers
            Console.WriteLine(s)
        Next
    End Sub
End Class

See Also