Skip to Content
Course content

38: Practice Exercise: Querying a Dataset with LINQ

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of LINQ as having a very efficient personal assistant who handles your filing cabinet. Instead of you manually opening every single folder, reading every page, and scribbling notes on a separate piece of paper to keep track of what you've found, you just give the assistant a specific set of instructions: "Go through the 'Invoices' drawer, pull out only the ones from last March that are over $500, sort them by the date they were received, and just give me a list of the customer names."

You don't care how the assistant flips the pages; you just care that the final list on your desk is exactly what you asked for. That's the core philosophy of LINQ (Language Integrated Query). We're moving away from the "how" (the manual foreach loop and if statements) and moving toward the "what" (the desired result).

Mapping the Assistant to the Code

When we translate that filing cabinet analogy into C#, each part of your request maps to a specific LINQ operator. It's a pipeline where data flows in one end and comes out the other, refined and trimmed.

  • "The Invoices drawer" is your data source—usually a List<T> or an array.
  • "Only the ones from last March over $500" is the .Where() clause. This is your filter. If a record doesn't meet the criteria, it's tossed out.
  • "Sort them by date" is .OrderBy() or .OrderByDescending(). This rearranges the remaining items without removing any.
  • "Just give me a list of the customer names" is .Select(). This is called a projection. You're telling C#, "I have the whole Order object, but I only actually want the string property called 'CustomerName'."

Slicing Through the Order Data

I've found that the best way to get comfortable with this is to stop thinking about loops and start thinking about "chains." Let's look at a scenario where we have a list of Product objects and we want to find the top 3 most expensive items in the "Electronics" category.


var expensiveElectronics = products
    .Where(p => p.Category == "Electronics")
    .Where(p => p.Price > 100)
    .OrderByDescending(p => p.Price)
    .Take(3)
    .Select(p => p.ProductName);

Notice how I used .Where() twice? You can do that. It's often cleaner to chain multiple filters than to write one giant, complex boolean expression. I also added .Take(3), which is the equivalent of telling the assistant, "Once you find the first three, stop looking."

One thing to keep in mind: LINQ uses "deferred execution." This means the query doesn't actually run the moment you define it. It only executes when you actually try to use the data—like when you foreach over the result or call .ToList(). It's a performance win because C# can optimize the query before it actually hits the data.




📋 Practical Task

Exercise: Filtering High-Value Electronics Orders

You are working on a reporting tool for an e-commerce warehouse. You have a list of Order objects, and your manager wants a specific report of "VIP Electronics Purchases."

Your Task: Write a LINQ query to process a list of orders based on these requirements:

  1. Filter the list to include only orders where the Category is "Electronics".
  2. Further filter to include only orders with a TotalAmount greater than 1,000.
  3. Sort the results by OrderDate in descending order (most recent first).
  4. Project the result so that you only have a list of the OrderId values.

Starter Code:


public class Order
{
    public int OrderId { get; set; }
    public string Category { get; set; }
    public decimal TotalAmount { get; set; }
    public DateTime OrderDate { get; set; }
}

// In your main method:
List<Order> orders = new List<Order>
{
    new Order { OrderId = 1, Category = "Electronics", TotalAmount = 1200, OrderDate = new DateTime(2023, 1, 10) },
    new Order { OrderId = 2, Category = "Books", TotalAmount = 50, OrderDate = new DateTime(2023, 1, 11) },
    new Order { OrderId = 3, Category = "Electronics", TotalAmount = 800, OrderDate = new DateTime(2023, 1, 12) },
    new Order { OrderId = 4, Category = "Electronics", TotalAmount = 1500, OrderDate = new DateTime(2023, 1, 15) },
    new Order { OrderId = 5, Category = "Home", TotalAmount = 2000, OrderDate = new DateTime(2023, 1, 16) }
};

// WRITE YOUR LINQ QUERY HERE
var vipElectronicsIds = // ... your code ...

// The expected output for this dataset should be: [4, 1]
Rating
0 0

There are no comments for now.

to be the first to leave a comment.