Mike Howe
Mike Howe

Reputation: 263

Confused on a LINQ where clause

public ViewResult List(string category, int page = 1) 
{
    ProductsListViewModel viewModel = new ProductsListViewModel
    {
        Products = repository.Products
            .Where(p => category == null || p.Category == category)
            ...........

The line : .Where(p => category == null || p.Category == category) is a little confusing to me. The logic is : "If category is null, then only select the selected category". This is from a book, but is this the best way to write this? It's saying the category can be "null OR an category value". So if category contains a value, it will use that value to select the items and not null (null selects all items). I wrote this which is kind of useless but works and makes its clearer :

.Where(p => category == null ? category == null :
                               p.Category == category)

Am I getting this logic right?

Upvotes: 0

Views: 129

Answers (3)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

.Where(p => category == null || p.Category == category)

will be translated to SQL query something like this (not exactly):

where null is null or Category == null    // When not specified, show all because, null IS null = true
// or
where 'someCategory' is null or Category == 'SomeCategoy'  // filter by some category

Ternary will return a bool, and not a condition to construct SQL query

category == null ? category == null : p.Category == category    

Upvotes: 1

nvoigt
nvoigt

Reputation: 77295

.Where(p => category == null || p.Category == category)

There are two parts here, connected by an OR, which means one of them must be true, to result in true:

category == null 

The category given was null

p.Category == category

The category in question matches the category given

So it will select a p, if either the category given was null, or it matched the category of p.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

It's basically allowing the category filter to be optional - if the category parameter is non-null, then it has to match whatever you're looking at. Otherwise, just include all categories.

Upvotes: 4

Related Questions