C# LINQ Basics
LINQ (Language Integrated Query) lets you query and transform collections, like arrays and lists, using a clean, expressive syntax directly in C#. It's part of the System.Linq namespace.
LINQ methods like Where(), Select(), and OrderBy() let you filter, transform, and sort data without writing manual loops, making code shorter and more readable.
collection.Where(x => condition);
collection.Select(x => transform);Filtering with Where
Where() filters a collection based on a condition, returning only the elements that satisfy it. It uses a lambda expression, like `x => x > 5`, to define the condition.
Transforming and sorting
Select() transforms each element into a new form, and OrderBy()/OrderByDescending() sort a collection. These methods can be chained together for powerful queries.
using System;
using System.Linq;
class Program {
static void Main() {
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens));
}
}2, 4, 6Where() filters the array, keeping only the even numbers.
using System;
using System.Linq;
class Program {
static void Main() {
int[] numbers = { 1, 2, 3 };
var squared = numbers.Select(n => n * n);
Console.WriteLine(string.Join(", ", squared));
}
}1, 4, 9Select() transforms each number into its square.
Key points
- LINQ requires `using System.Linq;`.
- Where() filters elements based on a condition.
- Select() transforms each element into a new form.
- LINQ methods use lambda expressions like `x => x > 5`.
