1.Where 扩展的不足
if 繁杂
public IQueryable<Person> Query(IQueryable<Person> source, string name, string code, string address)
{
var result = source;
if(string.IsNullOrEmpty(name) == false)
result = source.Where(p => p.Name.Contains(name));
if (string.IsNullOrEmpty(code) == false)
result = source.Where(p => p.Code.Contains(code));
if (string.IsNullOrEmpty(address) == false)
result = source.Where(p => p.Code.Contains(address));
return result;
}
2.使用 WhereIf 扩展
public IQueryable<Person> Query(IQueryable<Person> source, string name, string code, string address)
{
return source
.WhereIf(p => p.Name.Contains(name), string.IsNullOrEmpty(name) == false)
.WhereIf(p => p.Code.Contains(code), string.IsNullOrEmpty(code) == false)
.WhereIf(p => p.Code.Contains(address), string.IsNullOrEmpty(address) == false);
}
栗子:
利用linq中的WhereIf扩展方法
例
1 | if (SearchControlMain.PostingID.HasValue) |
换成
query = query.WhereIf(
SearchControlMain.CategoryID.HasValue,
q => q.CategoryID == SearchControlMain.CategoryID
);