如果我不确定哪些属性我想要匹配,如何将Where表达式添加到LINQ查询?

Exp*_* be 0 c# linq asp.net

我有一种情况,我可能想按订单号或名称搜索.我知道我可以Where为我的LINQ查询添加一个表达式,但我只想为我正在搜索的属性添加它!我不知道在调用方法之前会提供哪个参数,那么如何添加正确的条件呢?

public JsonResult Search(int orderNo=0, string firstName="", string lastName="")
{
    if (orderNo >0){
        //add Condition
    }

    if (firstName.Length > 0){
        //add Condition
    }

    if (lastName.Length > 0){
        //add Condition
    }

    //get Result

    var result = Repository.Orders.Where(???).OrderByDescending(e=> e.orderNo);

    //return
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*tka 5

以下假设Repository.Orders正在返回一个IQueryable,但这个想法只是动态添加您需要的表达式.查询执行是延迟的,因此您可以在实际请求结果之前系统地构建它.

// You haven't executed the query yet, you can still build up what you need
var query = Repository.Orders;

if(orderNo >0){
    // You STILL haven't actually executed the query.
    query.Where(x => x.orderNo == orderNo);
}
if(firstName.Length > 0){
    query.Where(x => x.firstname == firstName);
}
if(lastName.Length > 0){
    query.Where(x => x.lastName == lastName);
}

// Even with this, you STILL aren't actually executing the query.
query.OrderByDescending(x => x.orderNo);

// You'll be executing and enumerating the results here, but that's OK because you've fully defined what you want.
return Json(query.ToArray(), JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)