0

我有一种情况,我可能想按订单号或名称进行搜索。我知道我可以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
}
4

4 回答 4

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);
于 2012-04-19T21:37:37.710 回答
3

假设您的存储库返回IQueryable,您可以根据需要编写查询:

var query = Repository.Orders;
if(orderNo > 0)
{
    query = query.Where( x => x.OrderId == orderNo);
}

if(firstName.Length > 0)
{
   query = query.Where( x => x.FirstName == firstName);
}
//...
于 2012-04-19T21:37:17.570 回答
1
var result = Repository.Orders.Where(x => 
    (firstName == null || firstName.Trim() == "" || x.FirstName.Contains(firstName)) 
    && (lastName == null || lastName.Trim() == "") || x.LastName.Contains(lastName)) 
    && (orderNo == 0 || x.OrderNo == orderNo)).OrderByDescending(x => x.OrderNo)

@Amit_g 的示例也可以,并且可以说更容易阅读。我喜欢在一个查询中完成所有操作。这是一个偏好问题。

于 2012-04-19T21:37:46.043 回答
1

如果您必须 AND 这些条件并假设您的存储库返回IQueryable(如果不更改它或添加另一个重载或其他东西)

var query = Repository.Orders

// Build where clause

if (orderNo >0){
    query = query.Where(o => o.OrderNo == orderNo);
}

if (firstName.Length > 0){
    query = query.Where(o => o.FirstName == firstName);
}

if (lastName.Length > 0){
    query = query.Where(o => o.LastName == lastName);
}

// Build OrderBy clause

query = query.OrderByDescending(o => o.orderNo);

// Execute Query

results = query.ToList();
于 2012-04-19T21:38:47.600 回答