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