Reputation: 9989
My MVC view currently displays the following
I would like to perform filtering with a linq based on user selection so i can display the filtered results only.
My controller is like
var Products = db.Products.AsQueryable();
public class FilterPageViewModel
{
public int?[] man { get; set; }
public int?[] size { get; set; }
public int?[] color { get; set; }
public decimal? minPrice { get; set; }
public decimal? maxPrice { get; set; }
public Sorting Sorting {get ; set; }
public Order Order {get; set; }
}
public ActionResult Index(int? CategoryID = 0,
int? page = 0,
FilterPageViewModel model = null)
{
//Manufacturer #############################################
if (model.man != null)
{
foreach (int? i in model.man)
{
if (i.HasValue)
{
//Do something here
}
}
}
//Size ######################################################
if (model.size != null)
{
foreach (int? i in model.size)
{
if (i.HasValue)
{
//Do something here
}
}
}
//Color ######################################################
if (model.color != null)
{
foreach (int? i in model.color)
{
if (i.HasValue)
{
//Do something here
}
}
}
}
I guess i should perform something like...
Where Brand is 'Nike' OR 'Salomon'
AND Size is 'L' OR 'XL' OR 'XXL'
AND Color is 'Red' OR 'Green' OR 'Blue'
Of course the text within '' above are id's and replaced for clarification purposes.
I am sorry if i have not made my self clear but my tongue language is not English.
Upvotes: 0
Views: 176
Reputation: 9714
You can do something along these lines since you have an IQueryable provider for your Linq to SQL.
var filteredProducts = Products;
if(model.man != null)
filteredProducts = filteredProducts.Where(x => (from man in model.man where man.HasValue() select man.Value).Contains(x.manId));
if(model.size != null)
filteredProducts = filteredProducts.Where(x => (from size in model.size where size.HasValue() select size.Value).Contains(x.sizeId));
//etc
var enumerate = filteredProducts.ToList();
Because you're working with an IQueryable, the filters won't be evaluated until you actually enumerate the object with a call like ToList() or plug it into a foreach.
Upvotes: 4