CodeBlanks Logo Icon CodeBlanks

LINQ layer

C# course · Intermediate · Lesson 114/116

Use LINQ for data filtering and reporting.

Finding books with LINQ

Adding a FindByAuthor method to Library lets you search by author using LINQ Where. The signature: public IEnumerable<Book> FindByAuthor(string author).

In the body write _books.Where(b => b.Author == author). It returns matching books as a lazy sequence, produced only when the caller starts a foreach.

Lazy sequences and foreach

The result of Where is an IEnumerable<Book>; it is not computed at once. A foreach yields the next match each step. On large lists this saves memory.

The result can be empty; foreach may not loop at all. You can also take a single result with FirstOrDefault(), which returns null when empty.

Exercise Add the FindByAuthor method

Add a FindByAuthor method to the Library class below: it filters by author using Where and returns IEnumerable<Book>. In Main add two books, call FindByAuthor and print titles with foreach.

Show example solution
Write public IEnumerable<Book> FindByAuthor(string author) { return _books.Where(b => b.Author == author); }. In Main write foreach (var b in lib.FindByAuthor("Dostoevsky")) Console.WriteLine(b.Title);
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
}

class Library
{
    private List<Book> _books = new List<Book>();

    public void Add(Book b) => _books.Add(b);

    public int Count => _books.Count;

    public IEnumerable<Book> FindByAuthor(string author)
    {
        return _books.Where(b => b.Author == author);
    }
}

class Program
{
    static void Main()
    {
        var lib = new Library();
        lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" });
        lib.Add(new Book { Title = "Karamazov Brothers", Author = "Dostoevsky" });
        foreach (var b in lib.FindByAuthor("Dostoevsky"))
        {
            Console.WriteLine(b.Title);
        }
    }
}

Test yourself

  1. Match the LINQ operator to its behavior

    Where
    Filter by condition
    Select
    Shape transform
    OrderBy
    Sort
    Count
    Return tally
  2. Complete the Where call

    return _books.____(b => b.Author == author);
    Show answer
    return _books.Where(b => b.Author == author);
  3. What does Where return?

    • A single value
    • A sorted sequence
    • Items matching the condition
    • Groups
    Show answer

    Items matching the condition — Correct. Where returns items matching the condition as a lazy sequence.

All lessons in Intermediate