2

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

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

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

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

请注意,(byte)DeviceOS.Androidandd2都不为空

编辑(解决方案):

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

2 回答 2

7

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

试试下面的。你不应该得到任何空引用异常。

List<UDIDInfo> d2Android = d2
    .Where(x => x != null)
    .Where(x => x.DeviceOS != null)
    .Where(x => x.DeviceOS == (byte)DeviceOS.Android)
    .ToList();
于 2013-11-06T20:15:31.953 回答
0

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

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

在这种情况下,如果 null 传递给 searchTerm,您可以检查 null 表达式,如下所示

Summaries = (from r in Summaries
          where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
          orderby r
          select r).ToArray();
于 2021-03-09T06:58:54.207 回答