简体   繁体   English

Linq XDocument返回基于2个属性值的元素列表

[英]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. 是否可以基于2个匹配的属性值返回元素列表。 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 这是示例xml结构

    <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 : 在与@Adil建议的相同Where子句中,或使用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. 我也将XAttribute.Value更改为(string)XAttribute以使其更安全。

You probably need to use or || 您可能需要使用或|| to get records where attribute name have either value1 or value2 . 获取属性namevalue1value2 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. 您拥有的语句将过滤掉属性名称为value1的记录,然后将属性名称应为value2的过滤器应用于过滤器,除非value1等于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");

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

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