Filtering, Ordering, and Projecting with LINQ

Get what you want from your data

Posted by Rodrigo Castro on December 17, 2024

LINQ makes it easy to select, sort, and shape your data.

🔎 Filtering with Where

1
var even = numbers.Where(n => n % 2 == 0);

🗂️ Ordering with OrderBy / OrderByDescending

1
2
var sorted = names.OrderBy(n => n);
var reversed = names.OrderByDescending(n => n);

💡 Projecting with Select

Transform each item in a collection.

1
2
3
var lengths = names.Select(n => n.Length);
foreach (var len in lengths)
    Console.WriteLine(len);

📝 Combined Example

1
2
3
4
5
6
7
string[] fruits = { "Apple", "Banana", "Cherry" };
var result = fruits
    .Where(f => f.Contains("a"))
    .OrderBy(f => f)
    .Select(f => f.ToUpper());
foreach (var fruit in result)
    Console.WriteLine(fruit);

💡 Try It!

From a list of numbers, print the square of all odd numbers in order:

1
2
3
4
5
6
int[] nums = { 1, 2, 3, 4, 5 };
var squares = nums.Where(n => n % 2 != 0)
                  .OrderBy(n => n)
                  .Select(n => n * n);
foreach (var s in squares)
    Console.WriteLine(s);

Next: Aggregation and grouping with LINQ!