设置ListBox项目数据格式c#

李明

对不起,如果标题让你因为我的英语不好而感到困惑。我有一个 ListBox,其中包含许多具有时间格式的项目(例如:00:02:22:33)我想将此时间格式转换为分钟

For example: 00:02:22:33 -> 02 hours = 120 minutes
                             33 seconds = 33/60 = 0.55 minutes
So result is 120+22+0.55 = 142.55

我正在尝试编写一种方法,例如:

public static void Timeconvert(ListBox l) 
   {   
     foreach (var item in l.Items)
     {
        int x, int y, int z;             //It just to show you my thought
        if(item.format = 00:x:y:z)       
          {                                  
           int result =  x*60 +y + z/60 ;
           item = result.Tostring();
          }
     } 
  } 

我是 C# 的新手,所以我尽可能详细地解释,所以请帮助我:(

丹尼尔毯子

只需将字符串解析为时间跨度并使用TotalMinutes属性。

var time = TimeSpan.Parse("00:02:22:33");
var convertedToMinutes = time.TotalMinutes;  //Returns 142.55

这将更新您的列表项

for (int i = 0; i < listBox1.Items.Count; i++)
{
    TimeSpan time = TimeSpan.Parse(listBox1.Items[i].ToString());
    listBox1.Items[i] = time.TotalMinutes;
}

或者,TryParse()可用于处理格式不正确的字符串:if (TimeSpan.TryParse(listBox1.Items[i].ToString(), out time)) { listBox1.Items[i] = time.TotalMinutes; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章