请参阅以下代码:
而不是有这么多if else语句:
List<T> GetTs(string createBy, bool isAdmin, string departmentCode, ...)
{
if(isAdmin)
{
if(!string.IsNullOrEmpty(createBy))
{
var query = context.table
.Where(x => string.compare(x.createBy, createBy, StringComparison.OrdinalIgnoreCase) == 0)
.ToList();
return query;
}
else
{
var query = context.table.ToList();
return query;
}
}
else
{
if(!string.IsNullOrEmpty(createBy))
{
var query = context.table
.Where(x => string.compare(x.departmentCode, departmentCode, StringComparison.OrdinalIgnoreCase) == 0)
.Where(x => string.compare(x.createBy, createBy, StringComparison.OrdinalIgnoreCase) == 0)
.ToList();
return query;
}
else
{
var query = context.table
.Where(x => string.compare(x.departmentCode, departmentCode, StringComparison.OrdinalIgnoreCase) == 0)
.ToList();
return query;
}
}
}
我可以这样做吗,而不是那么多if else语句:
var query = context.table
.Where(x => (!isAdmin)? string.compare(x.departmentCode, departmentCode, StringComparison.OrdinalIgnoreCase) == 0) : SKIP THIS '.Where')
.Where(x => (!string.IsNullOrEmpty(createBy))? string.compare(x.createBy, createBy, StringComparison.OrdinalIgnoreCase) == 0) : SKIP THIS '.Where')
//...
.ToList();
如果条件为假,如何告诉LINQ跳过.Where
?可能的?
Patrick Hofman对以下评论的建议起作用:
var query = context.table
.Where(x => (!isAdmin)? string.compare(x.departmentCode, departmentCode, StringComparison.OrdinalIgnoreCase) == 0) : true)
.Where(x => (!string.IsNullOrEmpty(createBy))? string.compare(x.createBy, createBy, StringComparison.OrdinalIgnoreCase) == 0) : true)
//...
.ToList();
答案 0 :(得分:4)
如果我理解意图(有条件地应用谓词),那么基本上:不同的构成:
IQueryable<Whatever> query = context.Table;
if(condition1)
query = query.Where(x => x.column1);
if(condition2)
query = query.Where(x => x.column2);
//...etc
var list = query.ToList();
您可以将其包含在像
这样的扩展方法中static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition,
Expression<Func<T,bool>> predicate)
=> condition ? query.Where(predicate) : query;
和
var list= context.Table.WhereIf(condition1, x => x.column1)
.WhereIf(condition2, x => x.column2)
// ...
.ToList();
但是,我可能不会这样做,因为在很多情况下它需要构建一个不必要的附加表达式树。