c# - Linq 解析器问题?

标签 c# linq

嗯, 我不确定是我错了还是 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/

相关文章:

c# - 林克。从多个表中选择

linq count/groupby 不工作

C# 从集合类访问对象的属性

c# - 如何使用 CaSTLe Windsor WCF 设施限制服务?

c# - Linq 查询返回 IQueryable<IEnumerable<User>> 而不是 IQueryable<User>

c# - 将代码动态附加到方法 .Net-Core

c# - Entity Framework 中多个相似实体类型的常见查询

c# - 多列数据转换

c# - WCF 客户端/服务器配置不匹配

c# - 不能在 LINQ 中隐式转换类型