Mark
Mark

Reputation: 2587

Lambda check for null

var pq = attributes.SingleOrDefault(a => a.AttributeName == PasswordQuestion").AttributeValue;

The above code will throw an error if null. What is the best way to handle this? The below code would work, but I can't help but feel there's a more graceful way?

var pq = (attributes.SingleOrDefault(a => a.AttributeName == "PasswordQuestion") != null) ? attributes.SingleOrDefault(a => a.AttributeName == "PasswordQuestion").AttributeValue : null;

Upvotes: 1

Views: 1185

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156524

I usually leverage the Select method for things like this:

var pq = attributes.Where(a => a.AttributeName == "PasswordQuestion")
            .Select(a => a.AttributeValue)
            .SingleOrDefault();

Upvotes: 6

Related Questions