查找从xml文件中提取的数字的平均值
本文关键字:数字 平均值 提取 xml 文件 查找 | 更新日期: 2023-09-27 18:09:23
我有从XML文件中提取数据的代码。我想找到每个提取值(XMax
, XMin
, YMax
, YMin
, ZMax
, ZMin
)的平均值/平均值
var query = from file in fileEntries
let doc = XDocument.Load(file)
let x = doc.Descendants("XAxisCalib").Single()
let y = doc.Descendants("YAxisCalib").Single()
let z = doc.Descendants("ZAxisCalib").Single()
select new
{
XMax = x.Element("Max").Value,
XMin = x.Element("Min").Value,
YMax = y.Element("Max").Value,
YMin = y.Element("Min").Value,
ZMax = z.Element("Max").Value,
ZMin = z.Element("Min").Value
};
我算的XMax的平均值对吗?
var Average1 =
from a in query
select new
{ AvgMaxX = a.Average(a => a.XMax) };
var averageMaximumX = query.Average(t => t.XMax);
var averageMinimumX = query.Average(t => t.XMin);
var averageMaximumY = query.Average(t => t.YMax);
var averageMinimumY = query.Average(t => t.YMin);
var averageMaximumZ = query.Average(t => t.ZMax);
var averageMinimumZ = query.Average(t => t.ZMin);
EDIT:将字符串转换为双精度或小数或其他类型:
var averageMaximumX = query.Average(t => double.Parse(t.XMax));
//OR: var averageMaximumX = query.Average(t => decimal.Parse(t.XMax));
但是我要在select:
中做select new
{
XMax = double.Parse(x.Element("Max").Value),
XMin = double.Parse(x.Element("Min").Value),
// etc.
有帮助吗http://csharpbasic.blogspot.com/2008/08/exploring-linq-functions-select-min-max.html
这里有一种方法可以破解你的答案,但我一点也不喜欢这样,我相信有合适的方法:
double aXMax = 0;
double aXMin = 0;
double aYMax = 0;
double aYMin = 0;
double aZMax = 0;
double aZMin = 0;
int count = (from file in fileEntries
let doc = XDocument.Load(file)
let x = doc.Descendants("XAxisCalib").Single()
let y = doc.Descendants("YAxisCalib").Single()
let z = doc.Descendants("ZAxisCalib").Single()
select new
{
aXMax += x.Element("Max").Value,
aXMin += x.Element("Min").Value,
aYMax += y.Element("Max").Value,
aYMin += y.Element("Min").Value,
aZMax += z.Element("Max").Value,
aZMin += z.Element("Min").Value
}).Count();
aXMax /= (double)count;
aXMin /= (double)count;
aYMax /= (double)count;
aYMin /= (double)count;
aZMax /= (double)count;
aZMin /= (double)count;
还没有测试过,但是它应该可以工作,即使它是如此丑陋…