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?
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.
See more on this question at Stackoverflow