C# LINQ Select — Complete Guide
In this tutorial, you'll learn about C# LINQ Select. We cover key concepts, practical examples, and best practices.
You have a list of objects and need a list of a single property. You write a foreach loop that extracts values into a new list. The LINQ Select method projects each element through a transform function, returning the transformed sequence.
Wrong
var names = new List<string>();
foreach (var user in users)
{
names.Add(user.Name);
}
Output: Works. Five lines for a simple projection.
Right
var names = users.Select(u => u.Name).ToList();
Output: Same list, one line. The lambda u => u.Name projects each user to their name.
Select also provides the index in the transform:
var indexed = users.Select((u, i) => $"{i + 1}. {u.Name}").ToList();
// ["1. Alice", "2. Bob", "3. Charlie"]
Chaining Select with other LINQ methods:
var result = users
.Where(u => u.IsActive)
.Select(u => new { u.Name, u.Email })
.ToList();
Prevention
- Use
Selectinstead offoreach+new listfor projections. - Use
.Select(x => x.Property)for extracting a single member. - Use
.Select(x => new { x.A, x.B })for anonymous type projections. - Use
.Select((x, index) => ...)when you need the element index. - Use
SelectManywhen each element produces multiple output elements. - Remember
Selectis lazy — materialize with.ToList()or.ToArray().
Common Mistakes with linq select
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Select is used in Doda Browser to transform raw API responses into view models. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro