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:
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)
}
);
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.