开发者

How to use LINQ to determine if specific attribute value exists?

I am programming in C# and working with an XDocument. Want to add an element into the tree if and only if there are no other elements that have the a matching attribute value.

For example, is there a LINQ expression that I can use to look at the element below and see if there already exists a foo element with the same name before I add it?

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

I want to do something like this...

while(myXDo开发者_开发知识库cument.Element("people").Elements("foo").Attribute("Name").Contains(myName))
{
    // modify myName and then try again...
}


This should work:

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

It will return true if there's an attribute Name that equals myName


You may want to look at IEnumerable.Any on the XDocument.Elements. This determines whether any element of a sequence satisfies a condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜