Lambda check for null
var pq =开发者_如何学JAVA 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;
I usually leverage the Select
method for things like this:
var pq = attributes.Where(a => a.AttributeName == "PasswordQuestion")
.Select(a => a.AttributeValue)
.SingleOrDefault();
精彩评论