我的lambda表达式没有产生我预期的结果

时间:2013-08-30 21:55:15

标签: c# lambda

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为空,AuthorId为0

2 个答案:

答案 0 :(得分:3)

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

如上所述,当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();

答案 1 :(得分:1)

问题在于运营商的优先级,特别是&amp;&amp;优先级高于||。因此,如果不花太多钱,请尝试以下方法:

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();