计算出平均时间

本文关键字:时间 计算 | 更新日期: 2023-09-27 18:15:32

我想找出平均时间的最佳方法(基本上是呼叫次数,我想找出平均值)

数据来自我正在循环的数据表。我不能完全弄清楚如何使用一个时间跨度虽然,我可以转换字符串从/到传递它像我下面?

TimeSpan total = default(TimeSpan);
foreach (DataRow row in dtChats.Rows)
{
    total += row["TotalTime"].ToString();
}
TimeSpan myAverage = total / dtChats.Rows.Count;
编辑:

对不起,row['TotalTime']是一个时间值,例如0:05:44表示5分44秒

计算出平均时间

这是一个LINQ版本,我相信它可以改进:

 DataTable dt = new DataTable();
 dt.Columns.Add("TotalTime", typeof(string));
 dt.Rows.Add("00:05:44");
 dt.Rows.Add("00:10:25");
 dt.Rows.Add("00:20:15");
 var average = TimeSpan.FromTicks((long)(dt.AsEnumerable()
            .Select(row => TimeSpan.Parse(row.Field<string>("TotalTime")))
            .Average(ts => ts.Ticks)));
 //00:12:08
            TimeSpan total = default(TimeSpan);
            foreach (DataRow row in dtChats.Rows)
            {
                //i have no idea what your data looks like coming in in the dataRow. your mileage may vary.
                //for now i'm assuming it contains milliseconds as a string
                total += TimeSpan.FromSeconds(Int32.parse(row["TotalTime"].ToString())*1000);
            }
            TimeSpan myAverage = TimeSpan.FromSeconds(total.TotalSeconds / dtChats.Rows.Count);

TimeSpan进行平均的建议,即创建TimeSpan的列表,并使用Average()方法获得Tick的平均值,并生成一个新的TimeSpan作为平均值,例如:

List<TimeSpan> times = new List<TimeSpan>();
foreach (DataRow row in dtChats.Rows)
    times.Add(TimeSpan.Parse(row["TotalTime"].ToString()));
long averageTicks = Convert.ToInt64(list.Average(ts => ts.Ticks));
TimeSpan myAverage = new TimeSpan(averageTicks);