liveBook · Manning

LINQ extension

As explained in .NET in Action, Second Edition

A LINQ extension is a query operation exposed as an extension method for filtering, transforming, ordering, partitioning, or otherwise processing sequences.

A LINQ extension is an operation exposed as an extension method for processing sequences. Common operations filter, transform, partition, order, group, combine, or convert enumerable data. section 5.2

Use LINQ extensions according to the result you need:

  • Restriction: Where filters an input enumerable. section 5.2
  • Projection: Select creates output elements from input elements. section 5.2
  • Partition: Take and Skip slice an input enumerable. section 5.2
  • Ordering: OrderBy and OrderByDescending sort the input. section 5.2
  • Grouping, set, and conversion operations include GroupBy, Distinct, Union, ToList, and ToArray. section 5.2

Ordering books from an EF Core context

foreach (var book in dbContext.Books.OrderBy(b => b.Id)) { Console.WriteLine($"\"{book.Title}\" has id {book.Id}"); } SaveChanges must run before this query if newly added books should appear: the DbSet exposes database contents, not additions that remain only in code. section 5.2

Listing 5.5 Adding Books to CatalogContext and getting ordered list
using ManningBooks;
  
using var dbContext = new CatalogContext();                  #1
dbContext.Add(new Book { Title = ".NET in Action" });        #2
dbContext.Add(new Book { Title = "API Design Patterns" });   #3
dbContext.Add(new Book { Title = "Grokking Simplicity" });
dbContext.Add(new Book { Title = "The Programmer's Brain" });
dbContext.SaveChanges();                                     #4
  
foreach (var book in dbContext.Books.OrderBy(b => b.Id))     #5
{
  Console.WriteLine($"\"{book.Title}\" has id {book.Id}");   #6
}

Inspect the complete EF Core example that adds books, saves them, and orders the resulting records by identifier. section 5.2

How .NET in Action, Second Edition covers it

How deep it goes
Defines enumerable and queryable collections, categorizes operators, and demonstrates ordering; it stops short of broader operator implementation details.
Examples
Uses an EF Core in-memory catalog, added Book entities, SaveChanges, and OrderBy over dbContext.Books.
What it assumes
Assumes basic C# and EF Core usage, while introducing IEnumerable, IQueryable, DbSet, and LINQ operator categories.
What you can do after
Apply LINQ operators to order and process EF Core collections while accounting for saved versus unsaved context data.
How it connects
Connects LINQ extensions with IEnumerable, IQueryable, DbSet, DbContext, and Entity Framework Core.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.