0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Select in C#: Syntax and Examples

Use LINQ Select in C# to transform each element in a collection into a new form by applying a function. It projects each item from the source sequence into a new sequence of results using a lambda expression inside Select.
📐

Syntax

The Select method takes a lambda expression that defines how to transform each element in the source collection. It returns a new collection with the transformed elements.

  • source.Select(item => transformation): Applies the transformation to each item.
  • The lambda expression defines the output for each element.
  • The result is an IEnumerable<U> of the transformed type.
csharp
var result = source.Select(item => item.Transformation());
💻

Example

This example shows how to use Select to convert a list of numbers into their squares.

csharp
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        var squares = numbers.Select(x => x * x);

        foreach (var square in squares)
        {
            Console.WriteLine(square);
        }
    }
}
Output
1 4 9 16 25
⚠️

Common Pitfalls

Common mistakes when using Select include:

  • Forgetting that Select does not modify the original collection but returns a new one.
  • Not enumerating the result, so no output is produced.
  • Using Select when you want to filter items; use Where instead.
csharp
using System;
using System.Linq;
using System.Collections.Generic;

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

        // Wrong: expecting original list to change
        numbers.Select(x => x * x);
        foreach (var num in numbers)
        {
            Console.WriteLine(num); // Prints original numbers, not squares
        }

        // Right: assign the result
        var squares = numbers.Select(x => x * x);
        foreach (var square in squares)
        {
            Console.WriteLine(square); // Prints squares
        }
    }
}
Output
1 2 3 4 5 1 4 9 16 25
📊

Quick Reference

  • Select: Projects each element into a new form.
  • Input: IEnumerable<T> source collection.
  • Output: IEnumerable<U> transformed collection.
  • Use: source.Select(x => transformation).
  • Remember: Does not change original collection.

Key Takeaways

LINQ Select transforms each element in a collection into a new form using a lambda expression.
Select returns a new collection and does not modify the original source.
Always assign or enumerate the result of Select to see the transformed data.
Use Select for projection, not filtering; use Where to filter elements.
The output type can differ from the input type depending on the transformation.