I have the following code to find xml elements that have a particular attribute value:
IEnumerable<XElement> elems =
xmlDoc.Descendants("elemName")
.Where(x =>
x.Attribute("attrName").Value
.Equals(
filename,
StringComparison.OrdinalIgnoreCase
)
);
The problem is that if the element does not have that attribute, according to the docs, it will return null and we'll get a crash when we try to do null.Value
.
I've rewritten it like this:
IEnumerable<XElement> elems =
xmlDoc.Descendants("elemName")
.Where(x =>
((x.Attribute("attrName") == null)
? ""
: x.Attribute("attrName").Value).Equals(
filename,
StringComparison.OrdinalIgnoreCase
)
);
But I think it's a bit ugly. Is there an idiomatic way of doing this - I imagine this is a fairly common operation? I suppose I could just do a regular loop.