Anonymous Types and Implicitly Typed Variables

In Example 21-1, when you retrieve the information from the collection, you retrieve the entire Book object, but you output only the title and author. That’s somewhat wasteful, because you’re retrieving more information than you actually need. Since you need just the title and author, it would be preferable to be able to say something like this:

IEnumerable<Book> resultsAuthor =
    from testBook in bookList
    where testBook.Author == "Jesse Liberty"
    select testBook.Title, testBook.Author;

That construction will cause an error, though, because your query can return only one type of object. You could define a new class—say, bookTitleAuthor—to hold just the two bits of information you need, but that would also be wasteful, because the class would get used in only one spot in your program, right here when you retrieve and then output the data. Instead, you can just define a new class on the fly, like this:

IEnumerable<Book> resultsAuthor =
    from testBook in bookList
    where testBook.Author == "Jesse Liberty"
    select new { testBook.Title, testBook.Author };

Notice that this class doesn’t have a name; it doesn’t really need one, because you’re using it only in this one spot. Therefore, this feature is called an anonymous type. Based on the select statement, the compiler determines the number and types of the properties for the class (two strings, in this case), and creates the class accordingly.

This code won’t work yet, though. You’re assigning the results ...

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.