O'Reilly logo

Learning C# 3.0 by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required