2

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();
Timothy Shields
  • 65,578
  • 17
  • 107
  • 158
Omar Meky
  • 596
  • 1
  • 5
  • 15

2 Answers2

7

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();
Timothy Shields
  • 65,578
  • 17
  • 107
  • 158
0

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();
logeshpalani98
  • 1,112
  • 9
  • 25