简体   繁体   中英

Linq XDocument return a list of elements based on 2 attribute values

Is it possible to return a list of elements based on 2 matching attribute values. I've tried the following with no success.

var query = xdoc.Root.Elements("Root")
.Where(x => x.Attribute("Name").Value == "Value1")
.Where(x => x.Attribute("Name").Value == "Value2")
.Select(x => (string)x.Element("ElementName");

Here's sample xml structure

    <Region Name="Leeds">
        <Group>
            <Data1>Some data 1</Data1>
            <Data2>Some data 2</Data2>
        </Group>
<Group>
            <Data1>Some data 1</Data1>
            <Data2>Some data 2</Data2>
        </Group>

    </Region>
    <Region Name="Armley">
        <Group>
            <Data1>Some data 3</Data1>
            <Data2>Some data 4</Data2>
        </Group>
    </Region>

Thanks in advance

You can either use || within the same Where clause as @Adil suggested, or use Contains :

var names = new [] { "Value1", "Value2" };

var query = xdoc.Root.Elements("Root")
                     .Where(x => names.Contains((string)x.Attribute("Name")))
                     .Select(x => (string)x.Element("ElementName");

I also changed XAttribute.Value to (string)XAttribute to make it more safe.

You probably need to use or || to get records where attribute name have either value1 or value2 . The statement you have will filter out records which have value1 for attribute name and then it will apply filter that attribute name should have value2 which is not possible unless value1 is equal to value2.

var query = xdoc.Root.Elements("Root")
.Where(x => x.Attribute("Name").Value == "Value1" || x.Attribute("Name").Value == "Value2")
.Select(x => (string)x.Element("ElementName");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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