简体   繁体   中英

NullReferenceException in LINQ Query

I am getting an unusual "NullReferenceException was unhandled by user code" error in this LINQ query:

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

I went ahead and added a null check and am still getting the error

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

Note that (byte)DeviceOS.Android and d2 are both not null

Edit (Solution):

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

What if x is null? That is, the enumerable d2 contains a null item.

Try the following. You shouldn't get any null reference exception.

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

avoid the argument null exception in LINQ like below

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

In this case, if null passed to searchTerm you can check the null expression like below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM