C# LINQ查询中的NullReferenceException

C# LINQ查询中的NullReferenceException,c#,linq,nullreferenceexception,C#,Linq,Nullreferenceexception,在此LINQ查询中,我收到一个异常的“用户代码未处理NullReferenceException”错误: List<UDIDInfo> d2Android = d2.Where(x.DeviceOS == (byte)DeviceOS.Android).ToList(); 如果x为空怎么办?也就是说,可枚举的d2包含null项 尝试以下方法。您不应该得到任何空引用异常 List<UDIDInfo> d2Android = d2 .Where(x => x

在此LINQ查询中,我收到一个异常的“用户代码未处理NullReferenceException”错误:

List<UDIDInfo> d2Android = d2.Where(x.DeviceOS == (byte)DeviceOS.Android).ToList();

如果
x
为空怎么办?也就是说,可枚举的
d2
包含
null

尝试以下方法。您不应该得到任何空引用异常

List<UDIDInfo> d2Android = d2
    .Where(x => x != null)
    .Where(x => x.DeviceOS != null)
    .Where(x => x.DeviceOS == (byte)DeviceOS.Android)
    .ToList();
List d2Android=d2
.其中(x=>x!=null)
.Where(x=>x.DeviceOS!=null)
.Where(x=>x.DeviceOS==(字节)DeviceOS.Android)
.ToList();

避免LINQ中的参数null异常,如下所示

Summaries = (from r in Summaries
          where r.Contains(SearchTerm)
          orderby r
          select r).ToArray();
Summaries = (from r in Summaries
          where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
          orderby r
          select r).ToArray();
在这种情况下,如果将null传递给searchTerm,则可以检查null表达式,如下所示

Summaries = (from r in Summaries
          where r.Contains(SearchTerm)
          orderby r
          select r).ToArray();
Summaries = (from r in Summaries
          where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
          orderby r
          select r).ToArray();

如果这是Linq to entities,那么x不能为null。@user2674389这可能是真的。我甚至没有注意到LINQtoEntities标签,因为问题中没有提及;添加x!=null使查询短路。d2是一个List@OmarMeky那么标签EntityFramework是错误的,因为它与EntityFramework没有任何关系。很公平,我添加了它,因为列表来自EF查询,但这与实体无关。你确定它是linq吗?什么类型是
d2
?如果
d2
为空,您希望看到什么?可能存在重复的