Saturday, November 5, 2011

Threading in C# : Ordering and Joining

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:

Console.WriteLine("Books by Jesse Liberty:");

foreach (var testBook in resultsAuthor)

{

Console.WriteLine("{0}, by {1}",

testBook.Title, testBook.Author);

}

}

}

}

Example 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 Ordering_Results

{

// simple book class

public class Book

{

public string Title { get; set; }

public string Author { get; set; }


No comments:

Post a Comment