Skip to main content

18. LINQ in C#

Level: Beginner

ℹ️ What You'll Learn
  • 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.Percentage meaning "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

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
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 }
};

var toppers = students
.Where(s => s.Percentage >= 80)
.OrderByDescending(s => s.Percentage)
.ToList();

Console.WriteLine("=== Toppers ===");
foreach (Student student in toppers)
{
Console.WriteLine($"{student.Name} - {student.Percentage}");
}

Console.WriteLine($"Passed: {students.Count(s => s.Percentage >= 35)}");
Console.WriteLine($"Failed: {students.Count(s => s.Percentage < 35)}");
Console.WriteLine($"Any fee pending: {students.Any(s => !s.FeesPaid)}");

public class Student
{
public string Name { get; set; } = "";
public string ClassName { get; set; } = "";
public double Percentage { get; set; }
public bool FeesPaid { get; set; }
}

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:

  1. Filter students in "10-B" only
  2. Get names using Select
  3. Sort by percentage descending
  4. Count failed students (percentage < 35)
  5. Find first student with fee pending (!FeesPaid)
  6. Group by class and print count per class

See how LINQ answers business questions about data.


ℹ️ Video Tutorial

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

  1. Use Where for filtering.
  2. Use Select for selecting required data.
  3. Use OrderByDescending for rankings.
  4. Use FirstOrDefault when data may be missing.
  5. Use Any for yes/no existence checks.
  6. 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

NeedLINQ Method
FilterWhere
Select fieldsSelect
SortOrderBy
Sort high to lowOrderByDescending
Count matching itemsCount
Check if any existsAny
Find first itemFirstOrDefault

🎯 Q1: What is LINQ?

LINQ is a C# feature used to query collections like lists and arrays.

🎯 Q2: What does Where do?

Where filters items based on a condition.

🎯 Q3: What does Select do?

Select chooses or transforms data from each item.

🎯 Q4: Difference between First and FirstOrDefault?

First throws error if item is missing. FirstOrDefault returns null/default.

🎯 Q5: Why use ToList?

ToList() executes the LINQ query and stores the result in a list.


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

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.

Next Article

Strings in C# ->

nexcoding.in