2014-11-04 62 views
1

我有細胞一個DataGridView包含與HH VARCHAR值:mm格式,當我需要做的這些值I使用該函數的總和的Varchar [HH:MM] SUM中的DataGridView

private void CalcTime 
{ 
    string span = dataGridView1.Columns["Horas"].ToString(); 
    double seconds = 0; 
    seconds = dataGridView1.Rows 
     .Cast<DataGridViewRow>() 
     .AsEnumerable() 
     .Sum(x => TimeSpan.Parse((x.Cells["Horas"].Value.ToString())).TotalSeconds); 
    string somat = ""; 
    double segundosc = seconds; 
    somat = string.Format(
     "{0:00}:{1:00}", 
     segundosc/3600, 
     (segundosc/60) % 60, 
     segundosc % 60); 
} 

如果這些值就像01:00或03:00那樣沒關係,但如果我有像01:30這樣的值,那麼總和就不起作用了。如下:enter image description here

我該如何讓它工作正確? Regards

+0

我不能複製這一點。總數應該是5:40,但你會得到6:40。有沒有額外的記錄,我們看不到?任何隱藏的東西? – 2014-11-04 12:28:37

+0

@GrantWinney我能夠複製它。 – juharr 2014-11-04 13:04:03

回答

2

問題是,秒的總和將是20400,當你除以3600時,你會得到5.666666。而且由於您的變量是double而您使用的格式爲{0:00},因此該值將變爲四捨五入。您需要將金額轉換爲int或使用Math.Floor

int seconds = (int)dataGridView1.Rows 
    .Cast<DataGridViewRow>() 
    .AsEnumerable() 
    .Sum(x => TimeSpan.Parse((x.Cells["Horas"].Value.ToString())).TotalSeconds); 

OR

somat = string.Format(
    "{0:00}:{1:00}", 
    Math.Floor(segundosc/3600), 
    (segundosc/60) % 60); 

而且你不需要在你的string.Format最後一個參數。

另一種選擇是轉換回TimeSpanTimeSpan.FromSeconds

double seconds = dataGridView1.Rows 
    .Cast<DataGridViewRow>() 
    .AsEnumerable() 
    .Sum(x => TimeSpan.Parse((x.Cells["Horas"].Value.ToString())).TotalSeconds); 
TimeSpan totalTime = TimeSpan.FromSeconds(seconds); 
string somat = totalTime.ToString(@"hh\:mm"); 
+0

非常感謝@juharr:D – Reznor13 2014-11-04 14:28:48

0

或者使用TimeSpan.Add方法,無需轉換成秒,回TimeSpan

TimeSpan all = New TimeSpan(0); 
foreach(DataGridViewRow dgvr In dataGridView1.Rows) 
{ 
    all = all.Add(TimeSpan.Parse(dgvr.Cells["Horas"].Value.ToString())); 
} 
string somat = all.ToString(@"hh\:mm"); 
+0

這太糟糕了,沒有'Enumerable.Sum(IEnumerable )'。但是你可以用'Enumerable.Aggregate'來做到這一點。 – juharr 2014-11-04 13:18:19

+0

@juharr,對不起,不明白爲什麼我需要'Enumerable.Sum()'這裏? – Fabio 2014-11-04 14:28:02

+0

你可以用'Enumerable.Agregate'替換'foreach'來求和值。我只是說這太糟糕了,沒有辦法在'TimeSpan'中使用'Enumerable.Sum'。 – juharr 2014-11-04 14:53:47