3

我正在学习 LINQ to XML,需要找到具有特定属性的元素的存在。目前我正在使用:

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;

我知道有一种更简洁的方法可以做到这一点,可能使用 Any(),但我不确定如何重写查询以使用它。有人有什么好的建议吗?谢谢。

4

3 回答 3

6
groupCollectionXml.Elements("Group").Any(
    vw=>(string)vw.Attribute("Name") == groupName
  );
于 2009-03-03T15:36:23.850 回答
2
groupCollectionXml.
    Elements("Group").
    Where(item=>String.
        Equals(item.Attribute("Name"), groupName, OrdinalIgnoreCase)).
    Any();

如果你想在一条线上

于 2009-03-03T15:28:11.170 回答
2

感谢其他两个答案。我将一个的简洁性与另一个的正确性结合起来,然后搅拌并想出了这个效果很好:

groupCollectionXml.Elements("Group").Any(
  vw => string.Equals(vw.Attribute("Name").Value, groupName, StringComparison.OrdinalIgnoreCase)
);
于 2009-03-30T10:57:38.160 回答