如何在列表中添加时间跨度值

时间:2013-06-28 06:55:54

标签: c# .net winforms c#-4.0

在下面的代码中,我将获得一个时间跨度值列表。我需要添加所有时间跨度值,并且该值必须存储在string中。如何实现这一点我尝试了很多,但我找不到答案。 在此先感谢。

  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");
                }
            }

2 个答案:

答案 0 :(得分:0)

假设您要将所有时间跨度的值添加到单个时间范围内。

DateTimeTimeSpan是不可变的结构。使用它们的所有操作都返回新实例。因此,您需要将操作结果存储在TimeSpan值中(通常只需更新exisintg即可)

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

TimeSpan.Addition Operator MSDN文章中详细介绍+的使用情况。

或者,您可以使用Enumerable.Aggregate

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

答案 1 :(得分:0)

您可以尝试类似

的内容
string s = String.Join(",",objList.Select(x => x.ToString()));

看看

String.Join Method

Enumerable.Select

使用objList.Select(x => x.ToString())可以确定所需的格式输出

Span.ToString Method (String)