Object reference An instance of an object error is not established when using FirstOrDefault

When I use this code below, I get an object reference error, it may be because there is no match for the spider. My question is: how to check for a null value in these situations

int fooID = foos.FirstOrDefault(f => f.Bar == "spider").ID; 

I use the same script for different conditions to extract different elements from a list, for example

 int fooID = foos.FirstOrDefault(f => f.Bar == "spider").ID; String fooDescription = foos.FirstOrDefault(f => f.Sides == "Cake").Description; 

Is there any other way to check for null values.

+6
source share
2 answers

Just as usual, assign a variable and check it.

 var foo = foos.FirstOrDefault(f => f.Bar == "spider"); if (foo != null) { int fooID = foo.ID; } 

Based on your updated example, you will need to do this instead:

 var fooForId = foos.FirstOrDefault(f => f.Bar == "spider"); var fooForDescription = foos.FirstOrDefault(f => f.Sides == "Cake"); int fooId = fooForId != null ? fooForId.Id : 0; string fooDescription = fooForDescription != null ? fooForDescription.Description : null; // or string.Empty or whatever you would want to use if there is no matching description. 
+8
source

You can also use the DefaultIfEmpty extension DefaultIfEmpty for bevaiour if there are no matching elements. The following code demonstrates the use of

 string[] foos = {"tyto", "bar"}; var res = foos.Where(s => s.Length == 2) .DefaultIfEmpty("default") .First() .Length; Console.WriteLine (res); //will print the length of default, which is 7 
+1
source

All Articles