I'm getting some unexpected behavior in my process. I'm doing the following.
IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);
The above works and info tells me that the object isn't null. So I wish to check the number of the elements in subset by this.
IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);
String count = subset.Count();
Now I get an exception giving me the error message:
Object reference not set to an instance of an object.
What do I miss?!
It's possible that one of the Thing
's in subset
is null
. You can try this:
IEnumerable<Thing> subset = things.Where(a => a != null && a.SomeFlag);
Note that due to the way Linq's lazy evaluation, you won't get any exception you call .Where
because all it's doing at that point is setting up a condition for filtering the elements of things
. Only later when you call .Count
is it actually evaluating the results.
Update: With the new null-condition operator in C# 6 (also called the safe navigation or 'Elvis' operator), we can do the same thing a bit more succinctly:
IEnumerable<Thing> subset = things.Where(a => a?.SomeFlag);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With