Introduction to LINQ

Query data easily in C#

Posted by Rodrigo Castro on December 16, 2024

LINQ (Language Integrated Query) lets you work with data (like arrays and lists) using simple, readable queries.

📝 Why Use LINQ?

  • Write less code to filter, sort, and search data.
  • Works with lists, arrays, and even databases.

📋 Basic Example

1
2
3
4
int[] numbers = { 1, 2, 3, 4, 5 };
var evens = numbers.Where(n => n % 2 == 0);
foreach (var n in evens)
    Console.WriteLine(n); // 2, 4

🔍 LINQ Syntax Options

  • Method syntax: list.Where(...)
  • Query syntax: Like SQL!
1
2
3
var bigNumbers = from n in numbers
                 where n > 3
                 select n;

🌟 Common LINQ Methods

  • Where — filter
  • Select — project/transform
  • OrderBy — sort
  • FirstOrDefault — first value or default

💡 Try It!

Find the names that start with “A”:

1
2
3
4
string[] names = { "Alice", "Bob", "Anna" };
var aNames = names.Where(name => name.StartsWith("A"));
foreach (var name in aNames)
    Console.WriteLine(name);

Next: Filtering, ordering, and projecting with LINQ!