开发者

Lambda check for null

开发者 https://www.devze.com 2023-02-21 02:35 出处:网络
var pq =开发者_如何学JAVA attributes.SingleOrDefault(a => a.AttributeName == PasswordQuestion\").AttributeValue;
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

精彩评论

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