我正在尝试使用linq获取一定价格范围内的XML文件的值范围,我不太确定该怎么做,但是我知道如何获取每个Element的价格。
我试图列出每个元素的价格,然后应用范围内的所有价格,但是由于必须在价格范围内显示现有汽车的品牌,我不知道如何保留品牌。
XML:
<Garage>
<Car id="001">
<Brand>Foo</Brand>
<Price>100</Price>
</Car>
<Car id="002">
<Brand>Bar</Brand>
<Price>130</Price>
</Car>
<Car id="003">
<Brand>Re</Brand>
<Price>110</Price>
</Car>
</Garage>
码:
var xmlStr = File.ReadAllText(@"C:\Path\To\Xml");
var str = XElement.Parse(xmlStr);
var carInRange = str.Elements("Car").Where(x => x.Element("Price").Value.Equals("100")).ToList();
显然,我只是获得“ 100”值,但是我希望得到例如100到120之间的范围(仅作为示例),但不确定如何做到这一点。
您可能需要将价格解析为decimal
或其他数字类型。然后,您可以执行范围检查。例如
var carInRange = str.Elements("Car")
.Where(x => decimal.TryParse(x.Element("Price").Value, out decimal price)
&& price < 100m))
.ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句