开发者

Finding the average/mean value of numbers pulled from an xml file

I have code that extracts data out of an XML file. I want to find the average / mean value for each of the extracted values (XMax, XMin, YMax, YMin, ZMax, ZMin)

Here is how I extracted the six values:

var query = from file in fileEntries
            let doc = XDocument.Load(file) 
            let x = doc.Descendants("XAxisCalib").Single() 
            let y = doc.Descendants("YAxisC开发者_如何学编程alib").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 
            };

Am I on the right track with this average for 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: To convert the strings to doubles or decimals or whatever:

var averageMaximumX = query.Average(t => double.Parse(t.XMax));
//OR: var averageMaximumX = query.Average(t => decimal.Parse(t.XMax));

But I would actually do it in the select:

select new
{
    XMax = double.Parse(x.Element("Max").Value),
    XMin = double.Parse(x.Element("Min").Value),
// etc.


is that helpful http://csharpbasic.blogspot.com/2008/08/exploring-linq-functions-select-min-max.html


Here is one way to hack your way into getting your answers, but I don't like this at all and I'm sure there is a proper way :

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;

Haven't tested it out, but it should work, even though it's SO ugly...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜