Get XML elements with a particular attribute value I have the following code to find xml elements that have a particular attribute value:

IEnumerable&lt;XElement&gt; elems = 
    xmlDoc.Descendants("elemName")
    .Where(x =&gt; 
        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&lt;XElement&gt; elems = 
     xmlDoc.Descendants("elemName")
     .Where(x =&gt; 
         ((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.
I think you could use the null-conditional operator for x.Attribute("attrName").Value and swap arguments of String.Equals to avoid the NullReferenceException as follows:

IEnumerable&lt;XElement&gt; elems =
     xmlDoc.Descendants("elemName")
     .Where(x =&gt;
         filename.Equals(
             x.Attribute("attrName")?.Value,
             StringComparison.OrdinalIgnoreCase
         )
     );