Learn C# Β· 9/15

LINQ (Language Integrated Query)

7 min read

πŸ‘‹ Welcome Back, Developer!

Grab a cup of coffee β˜• (or tea, we don't judge). You’ve mastered the basics of C#, wrestled with loops, and survived arrays. Now, we are entering the territory that makes C# one of the most beloved languages in the industry.

Today we are talking about LINQ (pronounced "Link").

Fun Fact: Before LINQ (released in 2007 with .NET 3.5), C# developers often had to write literal SQL strings inside their C# code or write massive foreach loops just to find a user named "Bob." It was the dark ages. Anders Hejlsberg (the creator of C#) basically looked at SQL and said, "Why can't C# do that natively?" and thus, LINQ was born.


1. Introduction to LINQ: Querying Data Made Easy

πŸ“ Definition

LINQ (Language Integrated Query) is a set of technologies that extends C# with native query syntax. It introduces a pattern that allows you to write consistent code to query and transform data, whether that data comes from an in-memory collection (Lists, Arrays), a SQL database (via Entity Framework), or XML documents.

πŸ›‘ The Problem: The "For-Loop" Fatigue

Imagine you have a list of products, and you want to find all products that cost less than $50.

Without LINQ (The "Old School" Way):

csharp
List<Product> allProducts = GetProducts();
List<Product> cheapProducts = new List<Product>();

foreach (Product p in allProducts)
{
    if (p.Price < 50)
    {
        cheapProducts.Add(p);
    }
}
// Now cheapProducts has your data.
// That was a lot of typing for a simple question. πŸ˜“

This is Imperative Programming. You are telling the computer how to do it step-by-step (create list, loop, check if, add).

βœ… The Solution: Declarative LINQ

LINQ allows Declarative Programming. You tell the computer what you want, and let it figure out the how.

With LINQ:

csharp
var cheapProducts = allProducts.Where(p => p.Price < 50).ToList();

That's it. One line. Readable. elegant.

βš™οΈ Under the Hood: Deferred Execution

This is the most critical concept to understand for industry interviews.

When you write a LINQ query, it does not execute immediately. It just stores the instructions of the query. The data is not actually touched until you:

  1. Iterate over it (using a foreach loop).
  2. Force it to materialize (using methods like .ToList(), .ToArray(), or .Count()).

This is called Deferred Execution. It improves performance because if you define a complex query but never use the result, the CPU never wastes time calculating it.


2. Filtering and Sorting: Where and OrderBy

Now that we know why we use it, let's look at the bread and butter of data manipulation: getting only what you want, in the order you want it.

πŸ›‘ The Problem

You have a list of users. You need active users only, sorted by their signup date. Writing a sorting algorithm (like Bubble Sort or Quick Sort) manually is prone to bugs and is a waste of your precious time.

βœ… The Solution: Where and OrderBy

Let's set up a standard data set for our examples.

Setup (Boilerplate):

csharp
public class User
{
    public string Name { get; set; }
    public string Role { get; set; } // Admin, Member, Guest
    public int Age { get; set; }
}

// Our mock database
List<User> users = new List<User>
{
    new User { Name = "Alice", Role = "Admin", Age = 30 },
    new User { Name = "Bob", Role = "Member", Age = 25 },
    new User { Name = "Charlie", Role = "Guest", Age = 20 },
    new User { Name = "Diana", Role = "Admin", Age = 45 },
    new User { Name = "Evan", Role = "Member", Age = 18 }
};

Filtering with .Where()

The .Where() method expects a condition (a predicate) that returns true or false. It keeps items where the condition is true.

csharp
// Scenario: Find all Admins
// The "u => u.Role == 'Admin'" is a Lambda Expression.
// Read it as: "For each user 'u', check if u.Role equals 'Admin'"
var admins = users.Where(u => u.Role == "Admin").ToList();

// admins count is 2 (Alice, Diana)

Sorting with .OrderBy()

Sorting manually is painful. LINQ makes it trivial.

csharp
// Scenario: Sort users by Age (Youngest to Oldest)
var sortedByAge = users.OrderBy(u => u.Age).ToList();
// Result: Evan(18), Charlie(20), Bob(25)...

// Scenario: Sort by Age (Oldest to Youngest)
var sortedByAgeDesc = users.OrderByDescending(u => u.Age).ToList();
// Result: Diana(45), Alice(30)...

Industry Tip: You can chain these! This is called the "Method Syntax" or "Fluent API."

csharp
// Get Members, ordered by Name
var result = users
    .Where(u => u.Role == "Member")
    .OrderBy(u => u.Name)
    .ToList(); 

3. Projections: Selecting and Transforming Data (Select)

πŸ“ Definition

Projection refers to the operation of transforming an object into a new form. It's about taking the data you have and shaping it into the data you need.

πŸ›‘ The Problem

Your database might return a massive User object with 50 properties (PasswordHash, CreatedAt, LastLoginIP, etc.). Sending this entire object to the User Interface (UI) is a security risk and wastes bandwidth. You only need their Name and Role.

In the old days, you'd make a new list and map fields manually inside a loop.

βœ… The Solution: .Select()

.Select() projects each element of a sequence into a new form.

csharp
// Scenario: We only want a list of Names (Strings), not full User objects.
List<string> userNames = users.Select(u => u.Name).ToList();

// userNames = { "Alice", "Bob", "Charlie"... }

Advanced Industry Scenario: DTOs (Data Transfer Objects)
Ideally, you project into a lightweight class or an Anonymous Type.

csharp
// Projecting into an Anonymous Type (created on the fly)
var userSummaries = users.Select(u => new 
{
    FullName = u.Name,
    UserAge = u.Age
}).ToList();

foreach(var summary in userSummaries)
{
    // You can access properties just like a real class!
    Console.WriteLine($"{summary.FullName} is {summary.UserAge}");
}

Note: In Select, you are defining the shape of the output.


4. Aggregations: Count, Sum, Min, Max, and FirstOrDefault

Sometimes you don't want a list of data. You want a single value representing the data.

πŸ›‘ The Problem

Calculating the total revenue of a store or finding the oldest user usually involves initializing a variable (int sum = 0) and looping through everything to accumulate the value.

βœ… The Solution: Aggregate Methods

  1. Count(): Returns the number of elements.

    csharp
    int adminCount = users.Count(u => u.Role == "Admin"); // Returns 2
  2. Sum(): Adds up numeric values.

    csharp
    int totalYearsLived = users.Sum(u => u.Age); // Returns 138
  3. Min() / Max(): Finds the lowest or highest value.

    csharp
    int youngest = users.Min(u => u.Age); // 18
    int oldest = users.Max(u => u.Age);   // 45

⚠️ The Crash Handler: First vs FirstOrDefault

This is the most common interview question and production bug source regarding LINQ.

You want to find a specific user, say "Zorro".

  • .First(): Returns the first element that matches.
    • Risk: If no match is found (e.g., no user named "Zorro"), it throws an Exception and crashes your app. πŸ’₯
  • .FirstOrDefault(): Returns the first element that matches.
    • Safety: If no match is found, it returns the default value for the type (null for objects, 0 for integers). It does not crash. πŸ›‘οΈ

Industry Standard: Always use FirstOrDefault unless you are 100% logically certain the element must exist and want the program to fail if it doesn't.

csharp
// Dangerous
// User u = users.First(u => u.Name == "Zorro"); // CRASH! System.InvalidOperationException

// Safe
User u = users.FirstOrDefault(u => u.Name == "Zorro"); 
if (u != null) 
{
    // Logic here
}
else 
{
    Console.WriteLine("User not found.");
}

🧠 Recap & Best Practices

  1. LINQ replaces complex foreach loops with declarative queries.
  2. Deferred Execution: Queries don't run until you convert them (ToList, Count, etc.).
  3. Where filters data.
  4. OrderBy sorts data.
  5. Select transforms (projects) data into new shapes.
  6. FirstOrDefault is your safety net against crashing when finding items.

Imaginary Scenario:
Think of LINQ like ordering at a futuristic restaurant.

  • Old way: You walk into the kitchen, find the ingredients, chop the veggies, cook the steak, and plate it yourself.
  • LINQ: You tell the waiter: "I want the Steak (Source), cooked Medium Rare (Where), with a side of fries (Select), served immediately (ToList)."

πŸ”— Useful References (Bookmark These!)

Now go forth and query your data with elegance! πŸš€

Challenge

You are provided with a Product class and a List<Product> named products.

Your task is to write a single, chained LINQ query to perform the following operations in order:

  1. Filter the products list to include only those that belong to the "Electronics" category and have a StockQuantity of 10 or greater.
  2. Sort the filtered products in descending order based on their Price.
  3. Project the sorted list into a new sequence of anonymous objects, where each object contains only the Name (string) and Price (decimal) of the product.
  4. From this final sequence, retrieve only the very first element. If the sequence is empty after filtering, the result should be null.

Assign the final result of your query to the result variable.

Expected result

The solution should be a single, fluent LINQ statement that correctly chains the required operators. The variable result should be assigned the output of this chain.

A correct implementation would look like this:

csharp
var result = products
    .Where(p => p.Category == "Electronics" && p.StockQuantity >= 10)
    .OrderByDescending(p => p.Price)
    .Select(p => new { p.Name, p.Price })
    .FirstOrDefault();

Explanation:

  1. .Where(p => ...): This filters the list to keep only products where the Category is 'Electronics' AND the StockQuantity is 10 or more.
  2. .OrderByDescending(p => p.Price): This sorts the filtered results from the most expensive to the least expensive.
  3. .Select(p => new { ... }): This projects the sorted data into a new anonymous type, including only the Name and Price properties.
  4. .FirstOrDefault(): This is the crucial final step. It safely retrieves the first element from the projected sequence (which is the most expensive one due to the sorting). If the .Where() clause had returned no products, this method returns null instead of throwing an exception, which fulfills the requirements of the challenge.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.