使用 LINQ 对 XML 数据进行 AND 条件

问题描述 投票:0回答:1

我的 XML 数据看起来像这样(简化)

<customer>
   <id>01</id>
   <name>John</name>
   <discount id='plumb' />
   <discount id='lumber' />
</customer>
<customer>
   <id>02</id>
   <name>Susan</name>
   <discount id='fasten' />
   <discount id='lumber' />
</customer>
<customer>
   <id>03</id>
   <name>Paul</name>
   <discount id='garden' />
   <discount id='plumb' />
</customer>

我需要获取同时享有管道折扣和木材折扣的客户的姓名,即约翰,#1。有很多顾客,有很多不同的折扣。 我可以使用 LINQ 进行 OR 查询

var xml = XElement.Load(@"C:\customers.xml");
var result = from customer in xml.Descendants("customer")
from discount in customer.Descendants("discount")
where (string)discount.Attribute("id").Value == "plumb" || (string)discount.Attribute("id").Value == "lumber"
select customer.Descendants("name");

返回 John、Susan 和 Paul,但 ANDing 不返回任何内容,因为没有一个折扣 ID 可以同时等于“plumb”和“lumber”。

我一般不熟悉 LINQ。我十年前在一个项目中使用过它。我可以使用更详细的方法,迭代每个客户的折扣节点,但我宁愿寻求帮助。

c# xml linq
1个回答
0
投票

使用

from discount in customer.Descendants("discount")
会使事情变得复杂,因为此时您正在处理单独的折扣,而您的逻辑需要检查每个客户的多个折扣。

相反,这是编写查询的一种方法:

var result =
    from customer in xml.Descendants("customer")
    where customer.Descendants("discount").Any(discount => discount.Attribute("id").Value == "plumb")
       && customer.Descendants("discount").Any(discount => discount.Attribute("id").Value == "lumber")
    select customer.Descendants("name");

这将两张折扣支票放入一个

where
子句中,并与
&&
组合。

© www.soinside.com 2019 - 2024. All rights reserved.