繁体   English   中英

如何使用LINQ来确定是否存在特定的属性值?

[英]How to use LINQ to determine if specific attribute value exists?

我正在用C#编程并使用XDocument。 当且仅当没有其他元素具有匹配的属性值时,才想在树中添加元素。

例如,是否有一个LINQ表达式,我可以用它来查看下面的元素,看看在添加它之前是否已经存在一个具有相同名称的foo元素?

<people>
    <foo Name="Bob"> </foo>
    <foo Name="Larry"></foo>
    <foo Name="Tom"></foo>
</people>

我想做这样的事......

while(myXDocument.Element("people").Elements("foo").Attribute("Name").Contains(myName))
{
    // modify myName and then try again...
}

这应该工作:

XElement.Any(element => element.Attribute("Name").Value == myName)

如果存在Name等于myName的属性,它将返回true

您可能希望在XDocument.Elements上查看IEnumerable.Any 这确定序列的任何元素是否满足条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM