如果项目文本为空,则跳过查询的一部分

时间:2014-03-27 11:49:55

标签: c# linq

我有一个查询

            return uow.CustomerRepo
            .Get()
            .Where
            (
                c=>
                    c.Firstname.StartsWith(customerSearch.Initial) &&
                    c.Surname  == customerSearch.Surname           &&                        
                    c.Email    == customerSearch.Email             &&
                    c.Postcode == customerSearch.PostCode
            )

如果customerSearch中的某些内容为空,是否可以跳过部分查询?

所以我想跳过这部分

c.Surname  == customerSearch.Surname

如果

customerSearch.Surname

是空的

1 个答案:

答案 0 :(得分:4)

您可以使用明确检查customerSearch部分的条件来执行此操作:

.Where
(
    c=>
        (customerSearch.Initial == null || c.Firstname.StartsWith(customerSearch.Initial)) &&
        (customerSearch.Surname == null || c.Surname  == customerSearch.Surname)           &&                        
        (customerSearch.Email == null || c.Email    == customerSearch.Email)             &&
        (customerSearch.PostCode == null || c.Postcode == customerSearch.PostCode)
)

如果您需要检查空字符串而不是null,请相应地更改条件。