2017-04-18 119 views
-2

enter image description here基於潮頭ID的C#

如何總結datagridview的值,我試圖讓使用C#字典我的DataGridView的總結。但它只支持一個鍵和值。

ID | Weight 
301 | 75Kg 
302 | 80Kg 
302 | 80Kg 
301 | 43Kg 
304 | 600Kg 

結果應該是這樣的DataGrid中查看:

ID | Qty | Weight 
301  2  118Kg 
302  2  160Kg 
304  1  600Kg 

我只能得到ID和數量像上面。

Dictionary<string, KeyValuePair<int, decimal>> dic = new Dictionary<string, KeyValuePair<int, decimal>>(); 
 

 
       string cellValue = null; 
 
       decimal weight = 0; 
 
       for (int i = 0; i <= selecteddgv.Rows.Count - 1; i++) 
 
       { 
 
        if (!selecteddgv.Rows[i].IsNewRow) 
 
        { 
 
         cellValue = selecteddgv[1, i].Value.ToString(); 
 
         weight = Convert.ToDecimal(selecteddgv[5, i].Value); 
 
         if (!dic.ContainsKey(cellValue)) 
 
         { 
 
          dic.Add(cellValue, new KeyValuePair<int,decimal>(1, weight)); 
 
         } 
 
         else 
 
         { 
 
          dic[cellValue] += new KeyValuePair<int,decimal>(1, weight)); 
 

 
         }

我都試過,但說到在其他更新阻止它在「+ =」觸發一個錯誤

,並請幫助我如何顯示它成使用KeyValuePair後的datagridview。

+1

我不認爲需要SQL標記。請刪除它 – Biswabid

+1

問題不清楚? –

+0

你想修改內存中的數據嗎?還是想要一個適合的SQL查詢?告訴我們您目前如何將數據存入您的網格 – Marco

回答

0

如果你只是要求在SQL那麼這很簡單:

select id,count(*), sum(Weight) 
from [table] 
group by id; 
0

那麼有沒有關係,他們只需要一個鍵和值的字典。作爲一種「不理想」的解決方案,您可以創建一個嵌套字典。這本詞典的鍵持有的ID和值將是一個

KeyValuePair<int, string> 

是「詮釋」是「數量」和「弦」是「重量」

你過所有字典對象將是一個物體做出來的

Dictionary<int, KeyValuePair<int, string>> myDict = new Dictionary<int, KeyValuePair<int, string>>();