[RESOLVED]Problem in understanding an example on the pro Asp.net MVC 5 book

I am reading a book named Pro Asp.net MVC 5 , which is great , but I found the following code, which will show a lsit of products based on the selected category, and calculate the total number of items, as follow:-

public ViewResult List(string category, int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category == null ?
repository.Products.Count() :
repository.Products.Where(e => e.Category ==
category).Count()

But I got confused on why we need to do the following:-

TotalItems = category == null ? repository.Products.Count() : repository.Products.Where(e => e.Category == category).Count()

 and not just saying 

TotalItems = Products.count();

Because we already retrieve the Products based on the category, and there is no need to re-retrivng them to calculate their total !! Can anyone advice

The "Products" property of the ProductsListViewModel has all products where the category matches the category passed into the action if one is, but all products if it isn’t.  The line in question does the same thing.

x = a ? b : c

this means that if "a" is true then x will be "b" otherwise it will be "c".

So TotalItems will be just the number of products in the repository if no category has been passed in, but the number of products where the product has that category if a category has been passed in.

Leave a Reply