C#
What is LINQ?
Learn what LINQ is and how it queries collections.
What is LINQ?
LINQ (Language Integrated Query) is the standard way to query collections in C#. It lets you filter, transform and aggregate over an array, list or dictionary. LINQ methods extend the IEnumerable<T> interface, so they work directly with arrays and lists.
Core methods: Where filters, Select transforms, OrderBy sorts. You can chain them: numbers.Where(n => n > 5).Select(n => n * 2). The result is again a collection.
How LINQ works
LINQ methods are extension methods. They can be called on any collection that implements IEnumerable<T>: arrays, lists, dictionaries. Each method takes a lambda expression, a small function that runs for each element.
For example, in numbers.Where(n => n > 0) the lambda n => n > 0 runs for each number and keeps those that return true. The result is an IEnumerable<int>; you can loop with foreach or convert with .ToList().
Exercise Write your first LINQ query
In the numbers array below, filter the ones greater than 5 with Where and print each with Console.WriteLine in a foreach loop.
Show example solution
Filter with numbers.Where(n => n > 5), loop with foreach, print with Console.WriteLine(n).
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 3, 8, 1, 10, 5 };
foreach (var n in numbers.Where(n => n > 5))
{
Console.WriteLine(n);
}
}
}
Test yourself
-
What does LINQ make easier?
- Only connecting to a database
- Declaratively filtering, transforming and aggregating collections
- Auto-generating class definitions
- Coloring console output
Show answer
Declaratively filtering, transforming and aggregating collections — Correct. LINQ lets you write declarative queries over collections; filtering, transforming and aggregating are unified.
-
Complete the using directive
using System.Linq;
int[] numbers = { 1, 2, 3 };
var evens = numbers.____(n => n % 2 == 0);
Show answer
using System.Linq;
int[] numbers = { 1, 2, 3 };
var evens = numbers.Where(n => n % 2 == 0);
-
Match each method to its role
- Where
- Filters
- Select
- Transforms
- OrderBy
- Sorts
- First
- Gets the first element
Next lesson: Where