我试图找出按时完成平均值的最佳方法(基本上是我希望找出平均值的通话时间)
数据来自我循环的数据表。我无法解决如何使用TimeSpan的问题,我可以将字符串从/转换为通过它传递给我,如下所示?
TimeSpan total = default(TimeSpan);
foreach (DataRow row in dtChats.Rows)
{
total += row["TotalTime"].ToString();
}
TimeSpan myAverage = total / dtChats.Rows.Count;
编辑:
很抱歉,行[' TotalTime']是时间值,例如0:05:44,代表5分44秒
答案 0 :(得分:2)
这是一个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
答案 1 :(得分:1)
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);
答案 2 :(得分:1)
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);