LINQ中的空检查器

cas*_*las 0 c# linq

我有listItem和property的resData对象.我检查了所有列表项属性,所有这些属性都是.CoursesErrorCoursesErrornull

但是,当我签入以下内容时,它会返回true.

我想知道我错过了什么?

if(resData.Courses.Select(x => x.Error != null && x.Error.Length > 0).Count() > 0)
{
   Console.WriteLine("Error");
}
Run Code Online (Sandbox Code Playgroud)

oct*_*ccl 5

这是因为你正在使用a Select,你正在预测你的集合,没有应用条件,你应该使用Where,或者使用Count方法的重载:

if(resData.Courses.Count(x => x.Error != null && x.Error.Length > 0) > 0)
Run Code Online (Sandbox Code Playgroud)

正如@Chris指出的那样,如果您使用Any以避免枚举整个列表,那就更好了:

if(resData.Courses.Any(x => x.Error != null && x.Error.Length > 0))
Run Code Online (Sandbox Code Playgroud)

  • 或者更好的是使用"Any"来节省必须进一步通过集合而不是需要(`Where`和`Count`将打扰枚举整个列表). (3认同)
  • 这是真正的家伙,我要补充一点,我试图解释为什么这首先发生在他/她身上 (2认同)