开发者

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜