How to find an XML element by attribute using LINQ to XML?

I am learning LINQ for XML and must find the existence of an element with a specific attribute. At the moment I am using:

XElement groupCollectionXml = XElement.Parse(groupCollection.Xml);
IEnumerable<XElement> groupFind =
    from vw in groupCollectionXml.Elements("Group")
    where (string) vw.Attribute("Name") == groupName
    select vw;

if (groupFind.Count() == 0)
    return false;
else
    return true;

I know there is a more concise way to do this, possibly using Any (), but I'm not sure how to rewrite the request to use it. Anyone have any good advice? Thanks.

+3
source share
3 answers

Thanks to the other two answers. I combined the brevity of one with the correctness of the other, then moved and came up with this, which works well:

groupCollectionXml.Elements("Group").Any(
  vw => string.Equals(vw.Attribute("Name").Value, groupName, StringComparison.OrdinalIgnoreCase)
);
+2
source
groupCollectionXml.Elements("Group").Any(
    vw=>(string)vw.Attribute("Name") == groupName
  );
+6
source
groupCollectionXml.
    Elements("Group").
    Where(item=>String.
        Equals(item.Attribute("Name"), groupName, OrdinalIgnoreCase)).
    Any();

+2

Source: https://habr.com/ru/post/1704134/


All Articles