You are on page 1of 1

Basic query

The following example shows the basic usage of LINQ. In order to use a LINQ to Entities query, you will need to have a
collection (e.g., array of books) that will be queried. In this basic example, you need to specify what collection will be queried
("from <<element>> in <<collection>>" part) and what data will be selected in the query ("select <<expression>>" part). In
the example below, the query is executed against a books array, book entities are selected, and returned as result of queries.
The result of the query is IEnumerable<Book> because the type of the expression in the "'select << expression>>" part is
the class Book.

Hide   Copy Code

Book[] books = SampleData.Books;


IEnumerable<Book> bookCollection = from b in books
select b;

foreach (Book book in bookCollection )


Console.WriteLine("Book - {0}", book.Title);

As you might have noticed, this query does nothing useful - it just selects all books from the book collection and puts them
in the enumeration. However, it shows the basic usage of the LINQ queries. In the following examples you can find more
useful queries.

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.

You might also like