简体   繁体   English

Lambda表达式,以检查值是否为null或等于

[英]Lambda expression to check if value is null or equals

I am developing an Asp.Net MVC Application and i am new to Linq and CodeFirst. 我正在开发一个Asp.Net MVC应用程序,并且对Linq和CodeFirst还是陌生的。 In my controller this is the action that i have written: 在我的控制器中,这是我编写的动作:

public ActionResult Filter(int? PaperType , int? PaperGram , int? Brand)
{
    var FilteredResult ;
    if (PaperType.HasValue && PaperGram.HasValue && Brand.HasValue) {
        FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.PaperGram == PaperGram && m.Brand == Brand);
    }
    else if (PaperType.HasValue && PaperGram.HasValue) {
        FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.PaperGram == PaperGram);
    }
    else if (PaperType.HasValue && Brand.HasValue) {
        FilteredResult = db.Stocks.where(m => m.PaperType == PaperType && m.Brand == Brand);
    }
    // and ifs continue to last 
    /*
    .
    .
    .
    .
    */
    else {
        FilteredResult = db.Stocks;
    }

    return View(FilteredResult);
}

But i know that this is not the best way to do in Linq and Codefirst. 但是我知道这不是在Linq和Codefirst中最好的方法。 So, can you give a better solution to this problem? 那么,您能为这个问题提供更好的解决方案吗?

You can do this: 你可以这样做:

FilteredResult = db.Stocks.where(m => (m.PaperType == PaperType || !PaperType.HasValue)
                                   && (m.PaperGram == PaperGram || !PaperGram.HasValue) 
                                   && (m.Brand     == Brand     || !Brand.HasValue));

What you want to avoid is code duplication. 您要避免的是代码重复。
Create your original IQueriable and then add your where clauses when necessary 创建原始的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);
}

You can just assign all elements to list and then filter every element in each if condition 您只需分配所有元素到列表中,然后过滤每个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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM