JDavila JDavila - 1 month ago 11
C# Question

How to properly use C# Linq to get a filtered list?

Say for example I have C# LINQ query as below:

var allBooks = from book in books
select book;
var booksNonFiction = allBooks.Where(x => x.Genre = NonFiction)


In this example, I want to obtain all the
NonFiction
titles in
allBooks
collection. Am a bit unsure about the lambda expression.

Answer

To understand the way how to think in lambda expression it helped me a lot to translate the "x =>" into "every x in the sequence"

In your example AllBooks is a sequence of books. So your statement:

var booksNonFiction = allBooks.Where(x => x.Genre == NonFiction) 

would translate into: "From the sequence of all books, take "every book where book.genre equals nonfiction"

If you have more difficult linq statements it helps if you use plural nouns for your sequences (collections), and singular nouns for the parameters of the lambda expression (where you used x). This helps you remember the thing every x means.

var nonFictionBooks = allBooks.Where(book => book.Genre == NonFiction)

Here you can see that book is one element of the collection allBooks.

var frontPages = allBooks.Where(book => book.Genre == NonFiction)
    .Select(book => book.FirstPage)

Even though you might not now the Select statement yet, you can understand that it means that from every "book" in the collection of allBooks, you should take book.FirstPage.

To help understand the possibilities of Linq the article The Standard Linq operators helped me to learn the most used Linq statements

Linq heavily leans on extension methods. If you are not familiar with this, the following might help: Extension Methods Demystified

Comments