LINQ (Language Integrated Query) is one of the coolest features in C#. It lets you query and manipulate data collections using a clean, readable syntax. Once you get used to it, you will never want to go back to manual loops.
Basic LINQ Query
List<int> numbers = new List<int> { 5, 3, 8, 1, 9, 2, 7 };
// Get all even numbers
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
foreach (int n in evenNumbers)
{
Console.Write(n + " ");
}
// Output: 8 2
The query syntax looks a bit like SQL. from specifies the source, where
filters items, and select determines what to return.
Method Syntax (Fluent API)
Most C# developers prefer method syntax because it is more concise and chains nicely:
List<string> names = new List<string>
{
"Amina", "Bilal", "Chukwuemeka", "Fatima", "Emeka"
};
// Filter and transform
var shortNames = names
.Where(n => n.Length <= 5)
.OrderBy(n => n)
.ToList();
foreach (string name in shortNames)
{
Console.WriteLine(name);
}
// Output:
// Amina
// Bilal
// Emeka
// Fatima
The => is a lambda expression โ an anonymous function. n => n.Length <= 5
means "for each n, return true if n.Length is less than or equal to 5."
Common LINQ Methods
List<int> numbers = new List<int> { 10, 25, 30, 45, 50 };
// First and Last
int first = numbers.First(); // 10
int last = numbers.Last(); // 50
// Sum, Average, Count
int sum = numbers.Sum(); // 160
double avg = numbers.Average(); // 32
int count = numbers.Count(); // 5
// Min and Max
int min = numbers.Min(); // 10
int max = numbers.Max(); // 50
// Any and All
bool hasLarge = numbers.Any(n => n > 40); // true
bool allPositive = numbers.All(n => n > 0); // true
// Find
int found = numbers.Find(n => n > 20); // 25 (first match)
These methods are incredibly useful. Instead of writing loops to find the sum, average, or minimum of a list, you just call a method. Clean and readable.
Chaining Operations
List<string> words = new List<string>
{
"apple", "banana", "avocado", "blueberry", "apricot"
};
var result = words
.Where(w => w.StartsWith("a")) // Filter: starts with 'a'
.OrderBy(w => w) // Sort alphabetically
.Select(w => w.ToUpper()) // Transform to uppercase
.ToList();
foreach (string word in result)
{
Console.WriteLine(word);
}
// Output:
// APPLE
// APRICOT
// AVOCADO
The beauty of LINQ is how you chain operations together. Each method takes the output of the previous one and transforms it further. It reads almost like a sentence.