Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

linq

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(myXDocument.Element("people").Elements("foo").Attribute("Name").Contains(myName))
{
    // modify myName and then try again...
}
like image 786
PICyourBrain Avatar asked Nov 15 '10 20:11

PICyourBrain


2 Answers

This should work:

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

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

like image 73
wagi Avatar answered Nov 02 '22 19:11

wagi


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

like image 36
5 revs, 3 users 96% Avatar answered Nov 02 '22 20:11

5 revs, 3 users 96%