# Collections and LINQ — .NET Core: Build, Test and Ship Web APIs

Source: https://www.geekswithgeeks.com/en/dotnet-core/cs-collections-linq

> Filter, transform and aggregate collections with LINQ.

## Query a collection

LINQ (`System.Linq`) adds methods like `Where`, `Select` and `OrderBy` to any collection. They read like a pipeline and usually do not change the original list.

## A small pipeline

Keep the even numbers, square them, then print. Nothing runs until `ToList()` or a loop forces the query to execute.

```csharp
var nums = new List<int> { 1, 2, 3, 4, 5, 6 };
var result = nums.Where(n => n % 2 == 0)
                 .Select(n => n * n)
                 .ToList();
Console.WriteLine(string.Join(", ", result));
```

Output:

```
4, 16, 36
```

## Deferred execution surprise

A LINQ query is re-evaluated each time you enumerate it. If it hits a database or is expensive, call `ToList()` once and reuse the list.

**Quiz:** Which LINQ method keeps only items matching a condition?

- [ ] Select
- [ ] OrderBy
- [ ] GroupBy
- [x] Where

*Answer:* Where. `Where` filters; `Select` transforms each item into something else.
