Linq to SQL multiple conditional where clauses

后端 未结 3 1456
北恋
北恋 2020-12-01 19:39

At the moment I am retrieving my results as follows :

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


        
3条回答
  •  臣服心动
    2020-12-01 19:43

    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 GetFilteredClaims(string submissionId, string claimId,
                                         string organization, string status,
                                         string filterFromDate, string filterToDate,
                                         string region, string approver)
    {
        IQueryable 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();
    }
    

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

提交回复
热议问题