LINQ in C#: Querying Collections
C# and .NETbeginnerinterview-prep
Codevity Admin · 10/24/2026
Step 1 of 5 · C# and .NET Essentials
Codevity Admin · 10/24/2026
LINQ (Language Integrated Query) gives you one vocabulary for filtering, shaping and summarizing data, whether it lives in a , an XML document, or a database table queried through Entity Framework Core.
| Operator | Purpose |
|---|---|
| keep items that match a condition | |
| transform each item | |
| , | sort (add for reverse order) |
| split into groups by a key | |
| , | does at least one / does every item match? |
| , , | pick one item |
| , , , , | summarize |
| , | paging |
| remove duplicates |
A LINQ query is a recipe, not a result. Nothing runs until you enumerate it with , , , and so on.
This is powerful, but it has two consequences:
On an in-memory collection, LINQ runs as ordinary C# code. On an EF Core , the same operators are translated into SQL and executed by the database. The catch: once you convert to (for example by calling or ), the remaining operators run in memory.
List<T>WhereSelectOrderByThenByDescendingGroupByAnyAllFirstFirstOrDefaultSingleCountSumAverageMinMaxTakeSkipDistinctforeachToList()Count()First()ToList()First()FirstOrDefault()nullSingle()DbSetIEnumerableToList()AsEnumerable()Count() > 0Any()ToList()Wherevar people = new List<Person>
{
new("Asha", 31, "Pune"),
new("Ben", 24, "Delhi"),
new("Carla", 45, "Pune"),
};
var names = people
.Where(p => p.Age >= 30) // filter
.OrderBy(p => p.Name) // sort
.Select(p => p.Name) // project to just the names
.ToList(); // run the query now
Console.WriteLine(string.Join(", ", names)); // Asha, Carla
public record Person(string Name, int Age, string City);var byCity = people
.GroupBy(p => p.City)
.Select(g => new { City = g.Key, Count = g.Count(), AverageAge = g.Average(p => p.Age) });var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1); // nothing has run yet
numbers.Add(4);
Console.WriteLine(query.Count()); // 3 - the query sees 2, 3 and 4// Filter in SQL, then bring back only matching rows
var recent = await db.Orders.Where(o => o.CreatedAt > cutoff).ToListAsync(ct);
// Brings back the whole table first, then filters in memory - avoid
var slow = (await db.Orders.ToListAsync(ct)).Where(o => o.CreatedAt > cutoff);