🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME 01POSTS 02COURSES 03ELECTRİCAL_ENERGY 04AUTOMOTİVE_ENGİNEERİNG 05TOOLS 06LAB 07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Introduction to LINQ

An elegant way to query collections: Where, Select, OrderBy, Average, Max, GroupBy and lambda expressions, on measurement data.

What is LINQ?

LINQ (Language Integrated Query) is a family of methods that lets you filter, sort, transform and summarize data sources such as lists, arrays and databases. What you would write by hand with a for loop and temporary variables, you say in a single line. To use it you need using System.Linq;; in new .NET projects this is already added automatically.

The lambda expression

The language of LINQ is lambdas. x => x > 22 is a small nameless method that means "given x, tell me whether x is greater than 22". The parameter is on the left of the arrow and the result is on the right.

Where: filter

double[] temperatures = { 21.5, 22.1, 20.9, 23.4, 22.8, 35.2, 19.8 };

var warm = temperatures.Where(t => t > 22);

foreach (var t in warm)
    Console.WriteLine(t);

Console.WriteLine($"Count: {warm.Count()}");
22.1
23.4
22.8
35.2
Count: 4

Select: transform

It turns every element into something else. From Celsius to Fahrenheit:

var fahrenheit = temperatures
    .Select(c => c * 9 / 5 + 32)
    .Take(3);       // only the first 3

foreach (var f in fahrenheit)
    Console.WriteLine($"{f:F1} °F");
70.7 °F
71.8 °F
69.6 °F

OrderBy and aggregate methods

Console.WriteLine(string.Join(", ", temperatures.OrderBy(t => t)));
Console.WriteLine($"Average: {temperatures.Average():F2}");
Console.WriteLine($"Highest: {temperatures.Max()}");
Console.WriteLine($"Lowest: {temperatures.Min()}");
Console.WriteLine($"Total: {temperatures.Sum():F1}");
19.8, 20.9, 21.5, 22.1, 22.8, 23.4, 35.2
Average: 23.67
Highest: 35.2
Lowest: 19.8
Total: 165.7

OrderByDescending sorts from largest to smallest. Average: 165.7 / 7 = 23.67.

Chaining

The beauty of LINQ is that you can connect the methods to one another. "Find the measurements warmer than 22 degrees, sort them from largest to smallest, take the first two":

var top = temperatures
    .Where(t => t > 22)
    .OrderByDescending(t => t)
    .Take(2)
    .ToList();

Console.WriteLine(string.Join(" and ", top));
35.2 and 23.4

ToList() turns the query result into a real list. Note: LINQ queries run lazily; nothing is calculated until you ask for the result with something like a foreach, ToList() or Count().

Any, All, First, FirstOrDefault

Console.WriteLine(temperatures.Any(t => t > 30));    // True: is there one above 30?
Console.WriteLine(temperatures.All(t => t > 15));    // True: are all of them above 15?

double firstWarm = temperatures.First(t => t > 22);          // 22.1; throws an ERROR if none is found
double none = temperatures.FirstOrDefault(t => t > 100);     // if none is found: the default, 0
Console.WriteLine(firstWarm);
Console.WriteLine(none);
True
True
22.1
0

If an element might not be found, use FirstOrDefault instead of First; it returns the matching default value.

On lists of objects, and GroupBy

var measurements = new List<Measurement>
{
    new("K1", 10), new("K2", 20), new("K1", 30), new("K2", 40), new("K3", 50)
};

var groups = measurements.GroupBy(m => m.Channel);

foreach (var g in groups)
{
    Console.WriteLine($"{g.Key}: count {g.Count()}, average {g.Average(m => m.Value):F1}");
}

record Measurement(string Channel, double Value);
K1: count 2, average 20.0
K2: count 2, average 30.0
K3: count 1, average 50.0

GroupBy groups the elements by the given key; each group's Key property gives the key. Notice that the record definition is placed at the end of the file (after the top-level statements).

Tip: First write it with a simple foreach, make sure it works, then convert it to LINQ. Split long LINQ chains that are hard to read into a few variables.

Warning: On an empty collection, Average(), Max() and First() throw an error. If it may be empty, check with Any() first.

Try it yourself

Create a List<int> with 10 values, like a list of grades. With LINQ, (1) find the ones above the average, (2) print the number of students who passed with 60 or above, (3) list the top three grades from largest to smallest. Do each one first with a foreach, then with LINQ, and compare them.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What does the Where method do?
2. What is the expression x => x * 2 called?
3. Which is preferred to safely get the first element of a list that might be empty?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.