C# 如何使用Linq创建过滤器?
我的MVC视图当前显示以下内容 我想根据用户选择使用linq执行过滤,以便仅显示过滤结果 我的控制器就像C# 如何使用Linq创建过滤器?,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我的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; } pub
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,为便于澄清,将其替换
如果我没有说清楚,我很抱歉,但我的母语不是英语。您可以按照这些思路做一些事情,因为您的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中之前,不会对过滤器进行计算。您可以按照这些思路进行操作,因为您的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();
因为你正在使用一个可查询的,直到你用一个调用(如Telistor)来枚举对象或将它插入到一个FURACH中时,过滤器才会被评估。
告诉我们你将如何得到所有产品的列表来设置基础。在psuedo linq中,您没有select。查询的where部分只包含要筛选的谓词,但输出是什么?Linq查询有一个select语句。也许这是一个玩这些例子的想法。这就是学习linq的人数。@Daan我现在将检查这些。通过调用enum在linq中进行过滤。其中(谓词)
其中enum
是一些IEnumerable
,谓词
是一些Func
,例如var evenNumbers=number。其中(number=>number%2==0)展示如何获得所有产品的基础列表。展示一些你所拥有的输入数据和你期望的输出。在psuedo linq中,您没有select。查询的where部分只包含要筛选的谓词,但输出是什么?Linq查询有一个select语句。也许这是一个玩这些例子的想法。这就是学习linq的人数。@Daan我现在将检查这些。通过调用enum在linq中进行过滤。其中(谓词)
Whereenum
是一些IEnumerable
,Predicate
是一些Func
,例如var evenNumbers=number。其中(number=>number%2==0)