嗯, 我不确定是我错了还是 linq 解析错误,但是如果我不使用额外的括号,下面的 linq 查询会返回我不想要的内容。
int? userLevel;
Guid? supervisorId;
List<int> levelsIds = new List<int>();
string hierarchyPath;
// init the vars above
// ...
var qry = from f in items
where userLevel.HasValue
? (f.IsMinLevelIdNull() || (levelsIds.Contains(f.MinLevelId)))
: true
&& supervisorId.HasValue
? (f.IsSupervisorIdNull() || (!f.ChildrenVisibility && (f.SupervisorId == supervisorId.Value))
|| (f.ChildrenVisibility && (hierarchyPath.IndexOf(f.SupervisorId.ToString()) >= 0)))
: true
select f;
这里的想法是在变量“userLevel”和“supervisorId”的存在下“激活”的两个条件 block 之间的 AND 中运行查询。
例如,如果 userLevel 和 supervisoId 都为空,则查询变为:
var qry = from f in items
where true && true
select f;
好吧,只有当我将 2 个三字母组括在额外的括号中时,这个查询才能正常工作:
var qry = from f in items
where (userLevel.HasValue
? (f.IsMinLevelIdNull() || (levelsIds.Contains(f.MinLevelId)))
: true)
&& (supervisorId.HasValue
? (f.IsSupervisorIdNull() || (!f.ChildrenVisibility && (f.SupervisorId == supervisorId.Value))
|| (f.ChildrenVisibility && (hierarchyPath.IndexOf(f.SupervisorId.ToString()) >= 0)))
: true)
select f;
问题是:为什么需要额外的括号?我的意见是 linq 解析器有问题。
最佳答案
来自 7.2.1 Operator precedence and associativity &&
在 之前被评估? :
关于c# - Linq 解析器问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9786873/