我的MVC视图目前显示以下内容
我想根据用户选择使用linq进行过滤,这样我才能显示过滤结果。
我的控制器就像
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
}
}
}
}
我想我应该执行类似的事情......
Where Brand is 'Nike' OR 'Salomon'
AND Size is 'L' OR 'XL' OR 'XXL'
AND Color is 'Red' OR 'Green' OR 'Blue'
当然,上面''中的文字是id,并且为了澄清目的而被替换。
如果我没有清楚自己,但我的舌头语言不是英语,我很抱歉。
答案 0 :(得分:4)
由于您的Linq to SQL具有IQueryable提供程序,因此您可以执行这些操作。
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();
因为您正在使用IQueryable,所以在您实际使用ToList()之类的调用枚举对象或将其插入foreach之前,不会对过滤器进行评估。