Projection/Selection of fields
Using LINQ, developers can transform a collection and create new collections where elements contain just some fields. The
following code shows how you can create a collection of book titles extracted from a collection of books.
Hide Copy Code
Book[] books = SampleData.Books;
IEnumerable<string> titles = from b in books
select b.Title;
foreach (string t in titles)
Console.WriteLine("Book title - {0}", t);
As a result of this query, IEnumerable<string> is created because the type of expression in the select part is string. An
equivalent example written as a select function and lambda expression is shown in the following code:
Hide Copy Code
Book[] books = SampleData.Books;
IEnumerable<string> titles = books.Select(b=>b.Title);
foreach (string t in titles)
Console.WriteLine("Book title - {0}", t);
Any type can be used as a result collection type. In the following example, an enumeration of anonymous classes is returned,
where each element in the enumeration has references to the book and the first author of the book: