[英]loop through specific attribute using xml linq and c# and get its lowest value
how do i get the lowest and highest value of the attribute value? 如何获得属性值的最低和最高值?
<parent>
<anothertag value="20" />
<body>
<monitor value="3" />
<mouse value="5" />
<chair>
<monoblock value="5" />
</chair>
</body>
</parent>
and this is my code 这是我的代码
string xml = "<parent>" +
"<anothertag value=\"20\"/>" +
"<body>" +
"<monitor value=\"3\"/>" +
"<mouse value=\"5\"/>" +
"<chair>" +
"<monoblock value=\"5\"/>" +
"</chair>" +
"</body>" +
"</parent>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine("value: " + doc.Descendants().ToList().Attributes("value").Min());
but im having an error saying 但我有一个错误的说法
At least one object must implement IComparable
您必须将每个属性值解析为int:
Console.WriteLine("value: " + doc.Descendants().ToList().Attributes("value").Select(a => int.Parse(a.Value)).Min());
尝试这个:
Console.WriteLine("value: " + doc.Descendants().Max(x => x.Attribute("value") == null ? 0 : (int)x.Attribute("value")));
If you need to get the highest and the lowest value of one specific attribute, then one of the best method to achieve that in O(n) is using Aggregate
extension method: 如果需要获得一个特定属性的最高和最低值,则在O(n)中实现此目标的最佳方法之一是使用
Aggregate
扩展方法:
var minMax= doc.Descendants()
.Where(e=>e.Attribute("value")!=null)
.Aggregate(new {
Min = int.MaxValue,
Max = int.MinValue
},
(seed, o) => new
{
Min = Math.Min((int)o.Attribute("value"), seed.Min),
Max = Math.Max((int)o.Attribute("value"), seed.Max)
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.