• Want to receive the latest contracting news and advice straight to your inbox? Sign up to the ContractorUK newsletter here. Every sign up will also be entered into a draw to WIN £100 Amazon vouchers!

Linq - checking for nulls

wurzel

Contractor Among Contractors
Joined
Aug 6, 2008
Messages
1,877
Likes received
6
Thanks received
5
Using the query syntax, how do you check if a collection is null?


var result = from e in response.entitlements where e != null
select new {...}

response.entitlements is an array & when it's null I get a null reference exception but according to MSDN this where clause should handle it
 
The e != null means it will include any elements in the collection that are not null. It does not account for a null collection which, if I understand correctly, is the cause of the problem here.

You could use the coalesce operator (??) to use an empty collection when the property value is null. For example if the type of the elements in the response.entitlements collection is Entitlement you'd do something like the following:

Code:
var result = from e in response.entitlements ?? Enumerable.Empty<Entitlement>() 
                  where e != null // this may no longer be necessary
                  select new {...}
 
Last edited: 22:45
Code:
var result = from e in response.entitlements ?? Enumerable.Empty<Entitlement>() 
                  where e != null // this may no longer be necessary
                  select new {...}

Excellent, just what I was looking for. Thanks.
 

Advertisers

Back
Top