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
