Reputation: 107
When I use this below code, I get object reference error, this might be because there is no match for "spider". My question is, How to check for null value in these situations
int fooID = foos.FirstOrDefault(f => f.Bar == "spider").ID;
I'm using this same scenario for different conditions for fetching different Items from the list like
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.
Upvotes: 7
Views: 9132
Reputation: 16393
The same way as you normally would, assign a variable and check it.
var foo = foos.FirstOrDefault(f => f.Bar == "spider");
if (foo != null)
{
int fooID = foo.ID;
}
Based upon your updated example, you would 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.
Upvotes: 8
Reputation: 23626
You may also want to use DefaultIfEmpty
extension method for bevaiour if there is no matching elements. Next code demonstrates the usage
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
Upvotes: 1