Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Using LINQ, developers can filter entities from a collection and create a new collection containing just entities

that satisfy a
certain condition. The following example creates a collection of books containing the word "our" in the title with price less
than 500. From the array of books are selected records whose title contains the word "our", price is compared with 500, and
these books are selected and returned as members of a new collection. In ''where <<expression>>'' can be used a valid C#
boolean expression that uses the fields in a collection, constants, and variables in a scope (i.e., price). The type of the
returned collection is IEnumerable<Book> because in the ''select <<expression>>'' part is the selected type Book.

Hide   Copy Code

Book[] books = SampleData.Books;


int price = 500;
IEnumerable<Book> filteredBooks = from b in books
where b.Title.Contains("our") && b.Price < price
select b;

foreach (Book book in filteredBooks)


Console.WriteLine("Book - {0},\t Price {1}", book.Title, book.Price);

As an alternative, the .Where() function can be used as shown in the following example:

Hide   Copy Code

Book[] books = SampleData.Books;


int price = 500;
IEnumerable<Book> filteredBooks = books.Where(b=> (b.Title.Contains("our")
&& b.Price < price) );

foreach (Book book in filteredBooks)


Console.WriteLine("Book - {0},\t Price {1}", book.Title, book.Price);

You might also like