1
courses = courses.Where(
                c => queryParameters.ShowInActive || c.Flags.Contains((ulong)CourseFlags.Active) 
                     &&
                     (queryParameters.AuthorId <= 0 ||
                      (c.Authors != null && c.Authors.Exists(a => a.ID == queryParameters.AuthorId)))
                     &&
                     (queryParameters.CategoryIDs == null || queryParameters.CategoryIDs.Count == 0 ||
                      (c.Tags != null && c.Tags.Any(t => queryParameters.CategoryIDs.Contains(t.ID)))
                      &&
                      queryParameters.CourseIDs == null || queryParameters.CourseIDs.Count == 0 ||
                      queryParameters.CourseIDs.Contains(c.ID))
                ).ToList();

问题是queryParameters.CourseIDS.Count()返回 157 但上面的 lambda 表达式返回 2500 条记录。我究竟做错了什么?

我还确保ShowInactive设置为 true 并且CategoryIDs为 null 并且AuthorId为 0

4

2 回答 2

3

tl; dr:你忘记了一些括号。

如前所述,当queryParamters.ShowInActive设置为true时,谓词返回true并返回您的所有记录。因此,将返回所有记录。您似乎想使用所有查询参数。为了清楚起见,尝试在这个复杂的查询中添加一些空格。或者考虑将其拆分为多个Where()调用。

courses = courses.Where(
              c => (
                    queryParameters.ShowInActive
                    ||
                    c.Flags.Contains((ulong)CourseFlags.Active)
              ) && (
                    queryParameters.AuthorId <= 0
                    || (
                        c.Authors != null
                        &&
                        c.Authors.Exists(a => a.ID == queryParameters.AuthorId)
                       )
              ) && (
                    queryParameters.CategoryIDs == null
                    ||
                    queryParameters.CategoryIDs.Count == 0
                    || (
                        c.Tags != null
                        &&
                        c.Tags.Any(t => queryParameters.CategoryIDs.Contains(t.ID))
                       )
              ) && (
                    queryParameters.CourseIDs == null
                    ||
                    queryParameters.CourseIDs.Count == 0
                    ||
                    queryParameters.CourseIDs.Contains(c.ID)
                   )
              )
            ).ToList();
于 2013-08-30T22:06:19.540 回答
1

问题在于运算符优先级,特别是 && 的优先级高于 ||。因此,不要在此花费太多,请尝试以下操作:

courses = courses.Where(
            c => (queryParameters.ShowInActive || c.Flags.Contains((ulong)CourseFlags.Active))
                 &&
                 (queryParameters.AuthorId <= 0 ||
                  (c.Authors != null && c.Authors.Exists(a => a.ID == queryParameters.AuthorId)))
                 &&
                 ((queryParameters.CategoryIDs == null || queryParameters.CategoryIDs.Count == 0 ||
                  (c.Tags != null && c.Tags.Any(t => queryParameters.CategoryIDs.Contains(t.ID))))
                  &&
                  (queryParameters.CourseIDs == null || queryParameters.CourseIDs.Count == 0 ||
                  queryParameters.CourseIDs.Contains(c.ID)))
            ).ToList();
于 2013-08-30T22:09:39.030 回答