C# LINQ
LINQ
When you have a list of data, you often want to ask questions about it. Which scores are 50 or more? What is the total? What are the names in alphabetical order?
You can answer these questions with loops and if statements, but it takes many lines of code. LINQ (Language Integrated Query) gives you methods that answer them in one line.
To use LINQ, include the System.Linq namespace at the top of the file:
Example
using System.Linq; // Include the namespace that holds LINQ
Here is the total of a list of scores, first with a loop, and then with the LINQ method Sum():
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
// With a loop
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine(total); // 312
// With LINQ
Console.WriteLine(scores.Sum()); // 312
You already used Sum(), Min() and Max() with arrays in the Sort Arrays chapter. LINQ works with both arrays and lists.
Filter With Where()
Where() keeps only the items that match a condition. You write the condition as a lambda, like you learned in the previous chapter:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = scores.Where(s => s >= 50);
foreach (int score in passed)
{
Console.WriteLine(score);
}
The lambda s => s >= 50 returns true for the scores that are 50 or more, so Where() keeps 80, 62 and 95.
The result of Where() is not a list, but you can loop through it with foreach. We use var, because the real name of the type is long.
To print the results on one line, use string.Join(). It joins the items into one string, with a separator (here ", ") between them:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = scores.Where(s => s >= 50);
Console.WriteLine(string.Join(", ", passed)); // 80, 62, 95
Change Each Item With Select()
Select() runs a lambda on each item, and returns the new values. Here, each name is changed to uppercase letters:
Example
List<string> names = new List<string> { "Liam", "Jenny", "Angie" };
var upper = names.Select(n => n.ToUpper());
Console.WriteLine(string.Join(", ", upper)); // LIAM, JENNY, ANGIE
The original list does not change. names still contains "Liam", "Jenny" and "Angie".
Sort With OrderBy()
OrderBy() sorts the items from low to high (or from A to Z). OrderByDescending() sorts from high to low:
Example
List<string> cars = new List<string> { "Volvo", "BMW", "Ford", "Mazda" };
var sorted = cars.OrderBy(c => c);
Console.WriteLine(string.Join(", ", sorted)); // BMW, Ford, Mazda, Volvo
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var highFirst = scores.OrderByDescending(s => s);
Console.WriteLine(string.Join(", ", highFirst)); // 95, 80, 62, 45, 30
The lambda says what to sort by. c => c means "sort by the item itself". To sort the cars by the length of their names, you could write cars.OrderBy(c => c.Length).
Unlike the Sort() method of a List, OrderBy() does not change the original list.
Get One Value
Some LINQ methods return one single value, instead of many items:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
Console.WriteLine(scores.Count(s => s >= 50)); // 3
Console.WriteLine(scores.Sum()); // 312
Console.WriteLine(scores.Average()); // 62.4
Console.WriteLine(scores.Min()); // 30
Console.WriteLine(scores.Max()); // 95
Console.WriteLine(scores.First(s => s >= 50)); // 80
| Method | Description |
|---|---|
Count() | Returns the number of items. With a lambda, it counts only the items that match |
Sum() | Returns the total of all items |
Average() | Returns the average value |
Min() | Returns the lowest value |
Max() | Returns the highest value |
First() | Returns the first item. With a lambda, it returns the first item that matches |
Chain Methods
You can call LINQ methods one after another. Each method works on the result of the method before it.
Here, Where() keeps the scores that are 50 or more, and then OrderBy() sorts them:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var result = scores.Where(s => s >= 50).OrderBy(s => s);
Console.WriteLine(string.Join(", ", result)); // 62, 80, 95
Methods like Where(), Select() and OrderBy() don't return a List. If you need a real list, for example to add more items with Add(), call ToList() at the end:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
List<int> passed = scores.Where(s => s >= 50).ToList();
passed.Add(70);
Console.WriteLine(string.Join(", ", passed)); // 80, 62, 95, 70
Query Syntax
LINQ can also be written in another way, called query syntax. It looks a bit like a sentence:
Example
List<int> scores = new List<int> { 45, 80, 62, 30, 95 };
var passed = from s in scores where s >= 50 select s;
Console.WriteLine(string.Join(", ", passed)); // 80, 62, 95
from s in scorestakes each itemsfrom the listwhere s >= 50keeps the items that matchselect ssays what to return
This gives the same result as scores.Where(s => s >= 50). Use the way you find easier to read. This tutorial uses the methods with lambdas.