DEV Community

Cover image for Mastering LINQ in C#: 12 Practical Examples Every .NET Developer Should Know
ToolBench
ToolBench

Posted on

Mastering LINQ in C#: 12 Practical Examples Every .NET Developer Should Know

If you're a .NET developer, you've probably written countless for and foreach loops to filter, search, sort, and transform collections.

Before LINQ (Language Integrated Query) was introduced in .NET 3.5, developers had to write repetitive looping logic for almost every data operation. While those approaches still work, they often make the code longer, harder to read, and more difficult to maintain.

LINQ changed that by introducing a clean, expressive, and powerful way to query data directly within C#.

Whether you're working with:

  • Lists
  • Arrays
  • Dictionaries
  • XML
  • Entity Framework Core
  • SQL Server
  • APIs

LINQ is one of the most valuable features you can master.

In this article, we'll explore 12 practical LINQ examples that every .NET developer should know, along with real-world use cases, best practices, performance tips, and common pitfalls.


📖 Table of Contents

  1. What is LINQ?
  2. Why Use LINQ?
  3. LINQ Query Syntax vs Method Syntax
  4. Sample Project
  5. Example 1 – Where()
  6. Example 2 – Select()
  7. Example 3 – OrderBy()
  8. Example 4 – FirstOrDefault()
  9. More LINQ Methods (Part 2)
  10. Best Practices
  11. Common Mistakes
  12. Interview Questions
  13. FAQs

What is LINQ?

LINQ stands for Language Integrated Query.

It allows developers to query collections using a consistent syntax directly within C#.

Instead of manually looping through data, you simply describe what you want.

Traditional approach:

List<Employee> result = new();

foreach (var employee in employees)
{
    if(employee.Department=="IT")
    {
        result.Add(employee);
    }
}
Enter fullscreen mode Exit fullscreen mode

LINQ approach:

var result = employees.Where(e => e.Department == "IT");
Enter fullscreen mode Exit fullscreen mode

The second example is:

  • Easier to read
  • Easier to maintain
  • Less error-prone
  • More expressive

Why Use LINQ?

Here are a few reasons why LINQ has become an essential part of modern .NET development.

✅ Less Code

Tasks that once required several lines of loops and conditionals can often be written in a single, readable statement.

✅ Better Readability

LINQ reads almost like English.

employees
.Where(e => e.Department=="IT")
.OrderBy(e => e.Name)
.Select(e => e.Name);
Enter fullscreen mode Exit fullscreen mode

Even someone new to the project can quickly understand the intent.

✅ Consistent API

The same LINQ methods work across:

  • Arrays
  • Lists
  • Dictionaries
  • Entity Framework
  • XML
  • In-memory collections

Once you learn LINQ, you can use it almost everywhere in .NET.


Query Syntax vs Method Syntax

LINQ provides two styles.

Query Syntax

var result =
from employee in employees
where employee.Department=="IT"
select employee;
Enter fullscreen mode Exit fullscreen mode

Method Syntax

var result =
employees.Where(e => e.Department=="IT");
Enter fullscreen mode Exit fullscreen mode

Which one should you use?

Microsoft supports both, but method syntax is generally preferred because:

  • It's more concise.
  • It supports all LINQ operations.
  • Most production codebases use it.
  • Entity Framework examples are primarily written using method syntax.

Throughout this article, we'll use method syntax.


Sample Data

We'll use the following Employee class throughout the examples.

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Department { get; set; }

    public decimal Salary { get; set; }

    public int Age { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Sample data:

var employees = new List<Employee>
{
    new Employee { Id=1, Name="Alice", Department="HR", Salary=50000, Age=28 },
    new Employee { Id=2, Name="Bob", Department="IT", Salary=85000, Age=34 },
    new Employee { Id=3, Name="Charlie", Department="Finance", Salary=72000, Age=31 },
    new Employee { Id=4, Name="David", Department="IT", Salary=95000, Age=38 },
    new Employee { Id=5, Name="Emma", Department="HR", Salary=61000, Age=27 }
};
Enter fullscreen mode Exit fullscreen mode

Now let's explore practical examples.


1. Filter Data Using Where()

The Where() method filters a collection based on a condition.

var itEmployees =
employees.Where(e => e.Department=="IT");
Enter fullscreen mode Exit fullscreen mode

Output

Bob
David
Enter fullscreen mode Exit fullscreen mode

Real-world use case

Imagine you're building an employee management portal.

Instead of loading every employee, you only want to display developers from the IT department.

Where() makes this incredibly simple.

Best Practice

Avoid writing multiple nested Where() calls when a single condition is enough.

Instead of:

employees
.Where(e=>e.Department=="IT")
.Where(e=>e.Salary>80000)
Enter fullscreen mode Exit fullscreen mode

Write:

employees.Where(e =>
e.Department=="IT"
&& e.Salary>80000);
Enter fullscreen mode Exit fullscreen mode

It's easier to read and avoids unnecessary method chaining.


2. Project Data Using Select()

Sometimes you don't need the entire object.

Suppose you're creating a dropdown list that only needs employee names.

var names =
employees.Select(e => e.Name);
Enter fullscreen mode Exit fullscreen mode

Output:

Alice
Bob
Charlie
David
Emma
Enter fullscreen mode Exit fullscreen mode

Why is this important?

Returning only the required fields reduces memory usage and improves performance.

This becomes even more important when using Entity Framework because SQL queries retrieve only the selected columns.


3. Sort Data Using OrderBy()

Need employees sorted by salary?

var result =
employees.OrderBy(e=>e.Salary);
Enter fullscreen mode Exit fullscreen mode

Highest salary?

var highest =
employees.OrderByDescending(e=>e.Salary);
Enter fullscreen mode Exit fullscreen mode

Sorting is commonly used in:

  • Reports
  • Product listings
  • Dashboards
  • Search results
  • Admin portals

4. Find the First Matching Record

Suppose you're searching for an employee by ID.

var employee =
employees.FirstOrDefault(e=>e.Id==2);
Enter fullscreen mode Exit fullscreen mode

If found:

Bob
Enter fullscreen mode Exit fullscreen mode

If no employee exists, the result is null.

Why use FirstOrDefault() instead of First()?

  • First() throws an exception if no record exists.
  • FirstOrDefault() safely returns null.

In most applications, FirstOrDefault() is the safer choice because it allows you to handle missing data gracefully.


➡️ In Part 2, we'll cover:

  • Any()
  • All()
  • Count()
  • GroupBy()
  • Distinct()
  • Max()
  • Min()
  • Average()
  • Sum()
  • Join()
  • Performance tips and deferred execution

🚀 Explore More Free Developer Tools

As developers, we often switch between multiple websites to format JSON, decode JWTs, compare text, generate UUIDs, or convert data between formats. I wanted a faster, privacy-friendly alternative, so I built ToolBenchApp.

👉 https://toolbenchapp.com/

ToolBenchApp is a growing collection of free browser-based developer tools designed to simplify everyday development tasks. Everything runs directly in your browser, helping you work faster without unnecessary downloads or uploads.

Some of the tools currently available include:

  • JSON Formatter & Validator
  • JSON ↔ XML Converter
  • JSON ↔ CSV Converter
  • JWT Decoder
  • Base64 Encoder/Decoder
  • UUID Generator
  • URL Encoder/Decoder
  • SQL Formatter
  • YAML Formatter
  • Text Difference Checker
  • HTML Formatter
  • Regex Tester
  • And many more...

I'm continuously adding new tools based on feedback from the developer community. If there's a utility you'd like to see, let me know—I’d love to build it.

Happy coding! 🚀

Top comments (0)