Ordering and Joining
As you saw in Chapter 20, you can also order the results of your queries, and join data from two different tables in your query. You have this same ability in your LINQ queries. For example, to retrieve the Book
objects in your collection, ordered by author name (author’s first name, since the author’s full name is a single string), you’d use this query:
var resultList = from myBook in bookList orderby myBook.Author select myBook;
That output will look like this:
Books by author: Head First C#, by Andrew Stellman C# 3.0 in a Nutshell, by Ben Albahari C# 3.0 Cookbook, by Jay Hilyard Learning C# 3.0, by Jesse Liberty Programming C# 3.0, by Jesse Liberty Programming C#, fourth edition, by Jesse Liberty
The full code for this example is shown in Example 21-4.
Example 21-4. Ordering the results of a query is simple; just use the OrderBy keyword
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_21_4_ _ _ _Ordering_Results { // simple book class public class Book { public string Title { get; set; } public string Author { get; set; } public string Publisher { get; set; } public int PublicationYear { get; set; } } class Program { static void Main(string[] args) { List<Book> bookList = new List<Book> { new Book { Title = "Learning C# 3.0", Author = "Jesse Liberty", Publisher = "O'Reilly", PublicationYear = 2008 }, new Book { Title = "Programming C# 3.0", Author = "Jesse Liberty", Publisher = "O'Reilly", PublicationYear = ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.