我正在开发一个Asp.Net MVC应用程序,我是Linq和CodeFirst的新手。在我的控制器中,这是我写的动作:
rdd.aggregateByKey(List[Val]())(
(acc, x) => x :: acc,
(acc1, acc2) => acc1 ::: acc2
)
但我知道这不是Linq和Codefirst的最佳方式。那么,你能为这个问题提供更好的解决方案吗?
答案 0 :(得分:2)
你可以这样做:
FilteredResult = db.Stocks.where(m => (m.PaperType == PaperType || !PaperType.HasValue)
&& (m.PaperGram == PaperGram || !PaperGram.HasValue)
&& (m.Brand == Brand || !Brand.HasValue));
答案 1 :(得分:1)
您要避免的是代码重复 创建原始IQueriable,然后在必要时添加where子句
public ActionResult Filter(int? PaperType, int? PaperGram, int? Brand)
{
var FilteredResult FilteredResult = db.Stocks.AsQueryable();
if(PaperType.HasValue)
{
FilteredResult = FilteredResult.where(m => m.PaperType == PaperType);
if(PaperGram.HasValue)
FilteredResult = FilteredResult.where(m => m.PaperGram == PaperGram );
if ( Brand.HasValue)
FilteredResult = FilteredResult.where(m => m.Brand == Brand);
}
return View(FilteredResult);
}
答案 2 :(得分:1)
您可以将所有元素分配到列表中,然后过滤每个if条件
中的每个元素IEnumerable<Stock> filteredResult = db.Stocks.AsQueryable();
if (PaperType.HasValue)
{
filteredResult = filteredResult.Where(m => m.PaperType == PaperType);
}
if (PaperGram.HasValue)
{
filteredResult = filteredResult.Where(m => m.PaperGram== PaperGram);
}
if (Brand.HasValue)
{
filteredResult= filteredResult.Where(m => m.Brand== Brand);
}
return View(FilteredResult.ToList());