18. LINQ in C#
Level: Beginner
- What LINQ is
- Filter collections using
Where - Select only needed data using
Select - Sort data using
OrderBy - Count and check data using
Count,Any - Find one record using
FirstOrDefault - Group students by class
LINQ means Language Integrated Query.
It helps us ask questions from collections.
Example:
var passedStudents = students.Where(s => s.Percentage >= 35).ToList();
This means:
Give me students whose percentage is 35 or more.
The Problem: Searching Lists Manually
Without LINQ:
List<Student> passed = new List<Student>();
foreach (Student student in students)
{
if (student.Percentage >= 35)
{
passed.Add(student);
}
}
With LINQ:
var passed = students.Where(s => s.Percentage >= 35).ToList();
Shorter and easier to read.
Quick Definitions
- LINQ - Language Integrated Query for filtering/sorting collections
- Query - Question asked to collection (find passed students, sort by name)
- Where - Filter items matching a condition
- Select - Choose or transform data from items
- OrderBy - Sort items ascending
- OrderByDescending - Sort items descending
- Lambda - Short function
s => s.Percentagemeaning "for each student s, use percentage" - Chaining - Using multiple LINQ methods together (Where then OrderBy)
- GroupBy - Organize items into groups by a field
- FirstOrDefault - Find first item or null if not found
Understanding Lambda Syntax
LINQ uses lambda syntax: s => s.Percentage
Meaning:
s = each student in list
=> = arrow means "get"
s.Percentage = the percentage from that student
Example:
// "For each student s, get the percentage"
students.Where(s => s.Percentage >= 35)
// Read as: "Where student's percentage >= 35"
Think of s as a temporary variable. LINQ creates this automatically for each item.
Sample Data
List<Student> students = new List<Student>
{
new Student { Name = "Sahasra", ClassName = "10-A", Percentage = 84.8, FeesPaid = true },
new Student { Name = "Priya", ClassName = "10-A", Percentage = 91.2, FeesPaid = true },
new Student { Name = "Arjun", ClassName = "10-B", Percentage = 62.5, FeesPaid = false },
new Student { Name = "Kiran", ClassName = "10-B", Percentage = 28.0, FeesPaid = true }
};
Where
Use Where to filter.
var passed = students.Where(s => s.Percentage >= 35).ToList();
var failed = students.Where(s => s.Percentage < 35).ToList();
var class10A = students.Where(s => s.ClassName == "10-A").ToList();
Select
Use Select to choose or transform data.
var names = students.Select(s => s.Name).ToList();
Example with new shape:
var summaries = students.Select(s => new
{
s.Name,
s.ClassName,
Result = s.Percentage >= 35 ? "Pass" : "Fail"
}).ToList();
OrderBy
Use OrderBy to sort ascending.
Use OrderByDescending to sort descending.
var byName = students.OrderBy(s => s.Name).ToList();
var toppersFirst = students.OrderByDescending(s => s.Percentage).ToList();
Count and Any
int totalStudents = students.Count;
int passedCount = students.Count(s => s.Percentage >= 35);
bool anyFeePending = students.Any(s => !s.FeesPaid);
FirstOrDefault
Use FirstOrDefault when item may or may not exist.
Student? Sahasra = students.FirstOrDefault(s => s.Name == "Sahasra");
if (Sahasra != null)
{
Console.WriteLine(Sahasra.Percentage);
}
else
{
Console.WriteLine("Student not found.");
}
GroupBy
Use GroupBy to group students.
var groups = students.GroupBy(s => s.ClassName);
foreach (var group in groups)
{
Console.WriteLine($"Class: {group.Key}");
Console.WriteLine($"Students: {group.Count()}");
}
Full Example: LINQ Student Report
When You'll Use This in SMS
LINQ finds answers in data.
Examples:
// Find passed students
students.Where(s => s.Percentage >= 35)
// Get only names
students.Select(s => s.Name)
// Top performers first
students.OrderByDescending(s => s.Percentage)
// Students by class
students.GroupBy(s => s.ClassName)
// Any fee pending?
students.Any(s => !s.FeesPaid)
// Find student by name
students.FirstOrDefault(s => s.Name == "Sahasra")
Real SMS queries:
"Give me all students in 10-A"
"Show top 5 scorers"
"Count failed students"
"Get all subjects with max marks > 100"
"Find student named Sahasra"
"Group students by class"
Real impact: Production SMS answers these questions 100 times per day. LINQ makes it easy to read and write.
Try This Now
Run the LINQ student report example above. Then experiment:
- Filter students in "10-B" only
- Get names using
Select - Sort by percentage descending
- Count failed students (percentage < 35)
- Find first student with fee pending (
!FeesPaid) - Group by class and print count per class
See how LINQ answers business questions about data.
LINQ explained: Where, Select, OrderBy, GroupBy, FirstOrDefault with student data. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Forgetting ToList()
LINQ queries run when used. Use ToList() when you want the result now.
Mistake 2: Using First when item may not exist
Prefer FirstOrDefault and check for null.
Mistake 3: Writing too much logic inside LINQ
Keep LINQ readable. Move complex logic to methods.
Best Practices
- Use
Wherefor filtering. - Use
Selectfor selecting required data. - Use
OrderByDescendingfor rankings. - Use
FirstOrDefaultwhen data may be missing. - Use
Anyfor yes/no existence checks. - Keep LINQ chains short for beginners.
Practice Task
From a student list:
- Get all passed students.
- Get all fee pending students.
- Sort students by percentage descending.
- Print only names using
Select.
Quick Revision
| Need | LINQ Method |
|---|---|
| Filter | Where |
| Select fields | Select |
| Sort | OrderBy |
| Sort high to low | OrderByDescending |
| Count matching items | Count |
| Check if any exists | Any |
| Find first item | FirstOrDefault |
LINQ is a C# feature used to query collections like lists and arrays.
Where filters items based on a condition.
Select chooses or transforms data from each item.
First throws error if item is missing. FirstOrDefault returns null/default.
ToList() executes the LINQ query and stores the result in a list.
Use ChatGPT, Claude, or Copilot to go deeper on C# LINQ. Try these prompts:
"Explain LINQ Where and Select using student examples""Give me 5 LINQ practice tasks""Explain FirstOrDefault and Any simply""Quiz me with 5 beginner questions about LINQ"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.