Lesson 128 min read
LINQ
Query your data like a search engine — right inside C#
What Is LINQ?
LINQ stands for Language Integrated Query. It lets you search, filter, sort, and transform collections using clean, readable syntax — kind of like writing SQL database queries, but for any collection in C#.
Imagine you have a list of 1,000 students. Without LINQ, you'd write loops, if-statements, and temporary variables. With LINQ, you write something like "give me all students over 18, sorted by GPA, and just their names." One line. Done.
Understanding time complexity helps you choose the right LINQ methods for large datasets. LINQ has two styles:
- Method syntax:
list.Where(...).Select(...)— more common, uses lambda arrows - Query syntax:
from x in list where ... select ...— looks like SQL
Both produce the same result. Most C# developers prefer method syntax, but query syntax is great for complex joins.
LINQ Basics — Where, Select, OrderBy
Powerful LINQ Methods
LINQ has dozens of methods. Here are the ones you'll use constantly:
.Where()— filter items that match a condition.Select()— transform each item into something else.OrderBy()/.OrderByDescending()— sort.GroupBy()— group items by a key.First()/.FirstOrDefault()— get the first matching item.Any()— is there AT LEAST ONE match? (returns bool).All()— do ALL items match? (returns bool).Count()— how many items match?.Sum()/.Average()/.Min()/.Max()— math on collections.Distinct()— remove duplicates.Take(n)/.Skip(n)— pagination
Any, All, First, Count, GroupBy
Chaining, Take/Skip, and Distinct
Note: ⚡ LINQ is lazy! Methods like .Where() and .Select() don't actually run until you iterate (foreach) or force evaluation (.ToList(), .Count(), .First()). This means LINQ only processes what it needs — if you Take(3), it stops after finding 3 matches, even from a million items.