如何在列表中添加时间跨度值 [英] How to add timespan values in list

查看:253
本文介绍了如何在列表中添加时间跨度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我将得到一个时间跨度值列表。我需要添加所有的时间跨度值,该值必须存储在string.How实现这里我尝试了很多,但我找不到这个答案。
感谢提前。

In the below code i will get a list of time span values. I need to add all the time span values and that value has to be stored in string.How to achieve this i tried a lot but I can't find answer for this. Thanks in Advance.

  List<TimeSpan> objList = new List<TimeSpan>();
        string  totalIntervalTime = string.Empty;
     private void Resume_Click(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(textBox2.Text))
                {
                    textBox3.Text = DateTime.Now.ToLongTimeString();
                    //objPausetmr.Tick += new EventHandler(objPausetmr_Tick);
                    //objPausetmr.Stop();
                    tmrObj.Start();
                    DateTime pausetime = Convert.ToDateTime(textBox2.Text);
                    DateTime startTime = Convert.ToDateTime(textBox3.Text);
                    TimeSpan difference = pausetime - startTime;
                    string intervalDifference = difference.ToString();
                    richTextBox1.Text = intervalDifference;

                    TimeSpan tltTime = TimeSpan.Zero;
                    objList.Add(difference);
                    foreach (TimeSpan tmVal in objList)
                    {
                        tltTime.Add(tmVal);
                    }
                    totalIntervalTime = tltTime.ToString();

                    //MessageBox.Show(interval_Time.ToString());
                }
                else
                {
                    MessageBox.Show("Please set the Pause time");
                }
            }


推荐答案

您要将所有时间范围的值添加到单一时间跨度。

Assuming you want to add values of all time spans into single time span.

DateTime TimeSpan 是不可变的结构体。所有使用它们的操作都会返回新实例。所以你需要将结果存储在一个TimeSpan值(通常只是更新exisintg一个很好)

DateTime and TimeSpan are immutable structs. All operations using them return new instances. So you need to store result of operation in a TimeSpan value (normally just updating exisintg one is fine)

  var totalTime = TimeSpan.Zero;
  foreach (TimeSpan currentValue in objList)
  {
       totalTime = totalTime + currentValue;
  }

+ 详情请参阅 TimeSpan.Addition操作员 MSDN文章。

Usage of + covered in details in TimeSpan.Addition Operator MSDN article.

或者,您可以使用 Enumerable.Aggregate

var totalTime = objList.Aggregate(
      (accumulatedValue,current) => accumulatedValue + current);

这篇关于如何在列表中添加时间跨度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆