问题描述:

What I want to do is to get the average value from xml node attributes with different time.

My xml is structured like this:

<logs>

<log value="1" dateTime="Sun, 09 Feb 2014 08:00 am CET"/>

<log value="1" dateTime="Sun, 09 Feb 2014 09:00 am CET"/>

<log value="1" dateTime="Sun, 09 Feb 2014 10:00 am CET"/>

<log value="5" dateTime="Sun, 09 Feb 2014 11:00 am CET"/>

<log value="3" dateTime="Sun, 09 Feb 2014 12:00 am CET"/>

<log value="7" dateTime="Sun, 09 Feb 2014 13:00 am CET"/>

<log value="3" dateTime="Sun, 09 Feb 2014 14:00 am CET"/>

</log>

I want to calculate the average value from the last 5 hours, and write the value in label. My code is like this:

xdoc2.Load("data.xml");

XmlNodeList n = xdoc2.GetElementsByTagName("log");

List<int> values = new List<int>();

foreach (XmlNode curr in n)

{

int date;

date = Convert.ToInt32(curr.Attributes["dateTime"].InnerText);

DateTime date1 = Convert.ToDateTime(date);

if (date1.Hour != date1.Hour)

values.Add(Convert.ToInt32(curr.Attributes["value"].InnerText));

}

double average = values.Average();

label4.Text = Convert.ToString(average);

How can I add the condition for calculating the average value for the last 5 hours? Any idea?

网友答案:

You can compare Dates with each other. For example:

        DateTime d = DateTime.Now.AddHours(-5);
        DateTime d2 = Convert.ToDateTime("23.01.2013");
        if (d > d2){
            MessageBox.Show(d.ToString() + " " + d2.ToString());
        } else {
            MessageBox.Show("nope");
        }

With comparison of dates, you can easily iterate through the xml and compare, if the date is smaller than DateTime.Now.AddHours(-5).

In your example it would be something like this:

 foreach (XmlNode curr in n)
        {
            int date;
            date = Convert.ToInt32(curr.Attributes["dateTime"].InnerText);
            DateTime date1 = Convert.ToDateTime(date);
            DateTime now = DateTime.Now.AddHours(-5);
            if (date1>=now)
               values.Add(Convert.ToInt32(curr.Attributes["value"].InnerText));
        }

Afterwards you can just do the Average-Calculation like you have already done:

        double average = values.Average();
        label4.Text = Convert.ToString(average);
网友答案:
var average = (from node in n
               let date = Convert.ToDateTime(Convert.ToInt32(node.Attributes["dateTime"].InnerText))
               orderby date 
               select Convert.ToInt32(curr.Attributes["value"].InnerText)
               .Take(5)
               .Average();
网友答案:
var fromDate = DateTime.Now.AddHours(-5);
label4.Text = xdoc2.Descendants("log")
                   .Where(x => DateTime.ParseExact(x.Attribute("dateTime").Value, @"ddd, dd MMM yyyy HH:mm a\m CE\T", CultureInfo.InvariantCulture) > fromDate )
                   .Average(x => Convert.ToInt32(x.Attribute("value").Value)).ToString();
相关阅读:
Top