Trung Pham
Trung Pham

Reputation: 243

How to query with Boolean using LINQ

I have a table with Sub-Categories of Bike (Mountain Bikes, Touring Bikes, Road Bikes, ...) and I created a column isSelected with Boolean data type. I want to set up in Database when isSelected = true each Sub-Categories is matched with it will be show on Homepage and vice versa.

IQueryable<ProductSubcategory> list = null;

if (Id == null)
{
    list = BikesDB.ProductSubcategories;
}
else
{
    int id = Id.Value;
    list = BikesDB.ProductSubcategories.Where(m => m.ProductSubcategoryID == id
                                                   && m.NameofBike == Name
                                                   && m.isSelected == true);
}

var bikes = list.AsEnumerable().Select(
             p => new Bike { Id = p.ProductSubcategoryID, Name = p.NameofBike });

var viewModel = new CategoriesIndexViewModel
                {
                    NumberOfModel = bikes.Count(),
                    NameofBike = bikes.Select(b=>b.Name).ToList(),
                    Bikes = bikes.ToList()
                };

return this.View(viewModel);

Upvotes: 0

Views: 173

Answers (1)

johnb003
johnb003

Reputation: 1909

Are you sure isSelected is actually set? I think your linq expression looks fine. It should already correctly only select items where isSelected == true.

I'd look at your list in the debugger right before the query is done and make sure it has what you think it has.

OR you're running the first branch: if (Id == null) and your list is not filtered by the isSelected condition.

Upvotes: 1

Related Questions