Reputation: 606
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();
Upvotes: 3
Views: 13479
Reputation: 1638
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();
Upvotes: 0
Reputation: 79621
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();
Upvotes: 8