C# LINQ Basics — Complete Beginner Guide
Learning Objectives
- Query in memory collections with LINQ
- Filter data with where
- Project new shapes with select
- Sort with orderby
- Summarize with aggregate style operators
What Is LINQ
LINQ stands for Language Integrated Query. It gives C# a uniform syntax for selecting, filtering, sorting, and transforming data whether the source is a list, array, database, or XML.
using System.Linq;
int[] numbers = { 5, 12, 8, 130, 44 };
var even = numbers.Where(n => n % 2 == 0);
foreach (int n in even)
{
Console.WriteLine(n);
}
The lambda expression n with percent equals zero describes each item you want to keep.
why LINQ Helps
Manual loops for every filter and transform grow noisy quickly. LINQ expresses intent in a declarative way and chains operations for readability.
| Task | Loop style | LINQ style |
|---|---|---|
| Filter | if inside for | where |
| Transform | manual copy | select |
| Sort | custom comparer logic | orderby |
| Sum | running variable | sum or aggregate |
where for Filtering
List<string> names = new List<string> { "Ana", "Bo", "Chloe", "Ad" };
var longNames = names.Where(n => n.Length > 2);
foreach (string n in longNames)
{
Console.WriteLine(n);
}
Multiple where calls can stack when rules compose.
var result = names
.Where(n => n.Length > 2)
.Where(n => n.StartsWith("A"));
select for Projection
select creates a new result shape from each element.
record Product(string Name, double Price);
List<Product> products = new List<Product>
{
new Product("Pen", 20),
new Product("Bag", 500),
new Product("Book", 150)
};
var labels = products.Select(p => p.Name + ": " + p.Price);
foreach (string label in labels)
{
Console.WriteLine(label);
}
The result is another sequence. Nothing executes until you enumerate it with foreach, ToList, or similar.
Select into anonymous types
var view = products.Select(p => new
{
p.Name,
Discounted = p.Price * 0.9
});
foreach (var row in view)
{
Console.WriteLine(row.Name + " " + row.Discounted);
}
Anonymous types are convenient for short lived projections inside methods.
orderby Sorting
int[] scores = { 70, 95, 80 };
var ascending = scores.OrderBy(s => s);
var descending = scores.OrderByDescending(s => s);
foreach (int s in ascending)
{
Console.Write(s + " ");
}
Console.WriteLine();
foreach (int s in descending)
{
Console.Write(s + " ");
}
Sorting strings and multiple keys
var sortedNames = names.OrderBy(n => n.Length).ThenBy(n => n);
ThenBy applies a secondary rule after the primary sort.
Aggregate Style Operators
These produce a single value from a sequence.
int[] nums = { 1, 2, 3, 4, 5 };
int total = nums.Sum();
int max = nums.Max();
int min = nums.Min();
double avg = nums.Average();
int count = nums.Count();
Console.WriteLine(total);
Console.WriteLine(max);
Console.WriteLine(min);
Console.WriteLine(avg);
Console.WriteLine(count);
Custom aggregate
int product = nums.Aggregate(1, (acc, n) => acc * n);
Console.WriteLine(product);
Aggregate takes a seed and a function that folds each element into the running result.
Chaining a Full Query
List<int> raw = new List<int> { 3, 1, 4, 1, 5, 9, 2 };
var report = raw
.Where(n => n > 1)
.OrderBy(n => n)
.Select(n => "v" + n);
foreach (string item in report)
{
Console.WriteLine(item);
}
Read chains from top to bottom the way you would describe the steps in English.
Deferred Execution
LINQ methods usually defer work until enumeration. That means you can build queries cheaply and run them when data is ready.
var query = numbers.Where(n => n > 2);
numbers.Add(10);
// query still reflects latest data when enumerated
Call ToList or ToArray to snapshot results immediately when needed.
Common Mistakes
Forgetting using System.Linq
Without the using directive, query operators will not resolve.
Enumerating repeatedly
Running the same heavy query many times can surprise performance. Materialize once with ToList when reusing.
Confusing where with if inside select
Put filtering in where and transformation in select to keep roles clear.
Key Takeaways
💡
- LINQ provides one readable syntax for common data tasks
- where filters, select transforms, orderby sorts
- Aggregate operators like Sum and Max reduce sequences to values
- Queries are often deferred until you enumerate them
- Chain small operators to express multi step logic clearly
Practice Questions
- Which LINQ operator keeps only items that satisfy a condition?
- How does select differ from where?
- Write a query that sorts names by length then alphabetically.
- What does Aggregate do that Sum does not cover generally?
- Given an array of prices, compute the average of values greater than 100 using LINQ.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions