LINQ Basics
LINQ lets you ask questions about a collection in a short, readable way, like 'show me only the red ones sorted by size'. It filters, sorts, and summarizes lists for you.
In this page:
Syntax
using System.Linq;
var result = collection
.Where(item => condition)
.Select(item => expression)
.ToList();
LINQ Basics
LINQ (Language Integrated Query) lets you filter, transform, and aggregate collections declaratively using methods like Where, Select, and OrderBy.
It's part of System.Linq and works over any IEnumerable<T>. LINQ queries are typically chained together to express data pipelines in a single readable statement.
Note:
LINQ methods are lazily evaluated — they don't run until you enumerate the result, e.g. with
foreach or .ToList().Example: LINQ Basics
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.ToList();
foreach (int n in evenSquares)
{
Console.WriteLine(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting that many LINQ queries run lazily, so the result is computed only when you enumerate it.
- Forgetting
using System.Linq;and getting a missing method error. - Calling
First()on an empty sequence, which throws; useFirstOrDefault().
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: