LINQ查询中的NullReferenceException

Oma*_*eky 2 c# linq nullreferenceexception

我在这个LINQ查询中得到一个不寻常的"NullReferenceException未被用户代码处理"错误:

List<UDIDInfo> d2Android = d2.Where(x.DeviceOS == (byte)DeviceOS.Android).ToList();
Run Code Online (Sandbox Code Playgroud)

我继续并添加了一个空检查,但仍然收到错误

List<UDIDInfo> d2Android = d2.Where(x => x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();
Run Code Online (Sandbox Code Playgroud)

请注意,(byte)DeviceOS.Android并且d2都不为空

编辑(解决方案):

List<UDIDInfo> d2Android = d2.Where(x => x != null && x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();
Run Code Online (Sandbox Code Playgroud)

Tim*_*lds 7

如果x是null怎么办?也就是说,可枚举d2包含一个null项目.

请尝试以下方法.您不应该获得任何空引用异常.

List<UDIDInfo> d2Android = d2
    .Where(x => x != null)
    .Where(x => x.DeviceOS != null)
    .Where(x => x.DeviceOS == (byte)DeviceOS.Android)
    .ToList();
Run Code Online (Sandbox Code Playgroud)