2012-03-20 100 views
2

那么, 我不知道如果我错了,或者如果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; 

这里的想法是在和条件“激活”两大块之间由变量“用户级”和“supervisorId”的存在运行查询。

例如,如果用户级和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解析器存在问题。

+0

与LINQ无关。去标记。 – leppie 2012-03-20 12:44:45

+0

关于LINQ的问题_is_,只是不是的答案。重新标记。 – 2012-03-20 14:13:55

回答

2

附加括号将作为优先在例如你的代码将如下面的,因为有真正& &之间无缝隙地评估错误的顺序评估需要被评估supervisorId.HasValue ...

var qry = from f in items 
     where 

     1st: userLevel.HasValue 

      ? 

     2nd: (f.IsMinLevelIdNull() || (levelsIds.Contains(f.MinLevelId))) 

      : 

     3rd: true && supervisorId.HasValue 
       ? (f.IsSupervisorIdNull() || (!f.ChildrenVisibility && (f.SupervisorId == supervisorId.Value)) 
        || (f.ChildrenVisibility && (hierarchyPath.IndexOf(f.SupervisorId.ToString()) >= 0))) **)** 
       : true 
     select f;