LINQ到SQL多条件where子句 [英] Linq to SQL multiple conditional where clauses

查看:95
本文介绍了LINQ到SQL多条件where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我取回我的结果如下:

At the moment I am retrieving my results as follows :

public List<claim> GetClaims()
{
    return _db.claims.OrderBy(cl => cl.claimId).ToList();
}

不过,我现在想起来要基于上面的列表视图我的筛选器添加到8有条件的where子句。

But now I am trying to add up to 8 conditional where clauses based on filters above my listview.

于是我变成了:

public List<claim> GetFilteredClaims(string submissionId, string claimId,
                                     string organization, string status,
                                     string filterFromDate, string filterToDate,
                                     string region, string approver)
{
    return _db.claims.Where(cl => cl.submissionId == 5).ToList();
}

我怎样才能做一个检查每个过滤器添加一个WHERE子句仅当它们包含的价值?

How can I do a check for each filter to add a where clause only if they contain a value?

推荐答案

有没有理由你不能只是保持致电。凡数次过滤结果。由于LINQ的延期执行到SQL它会在一个SQL语句执行:

There is no reason why you can't just keep filtering the results by calling .Where several times. Because of the deferred execution of LINQ to SQL it will all be executed in one SQL statement:

public List<claim> GetFilteredClaims(string submissionId, string claimId,
                                     string organization, string status,
                                     string filterFromDate, string filterToDate,
                                     string region, string approver)
{
    IQueryable<claim> filteredClaims = _db.claims;

    if (!string.IsNullOrWhiteSpace(submissionId))
    {
        filteredClaims = filteredClaims.Where(claim => claim.submissionId == submissionId);
    }

    if (!string.IsNullOrWhiteSpace(claimId))
    {
        filteredClaims = filteredClaims.Where(claim => claim.claimId == claimId);
    }

    ...

    return filteredClaims.ToList();
}

如果你永远都需要添加或条件,你可以看看 predicateBuilder

If you will ever need to add OR conditions, you could take a look at PredicateBuilder.

这篇关于LINQ到SQL多条件where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆