2015-10-18 27 views
0

我工作的事,我需要從數據庫中獲得一些價值觀和成DataTable. I have this a KeyValuePair`列表中聲明在KeyValuePair設置值默認值

List<KeyValuePair<int, int>> thisList = new List<KeyValuePair<int, int>>(); 

thisList的關鍵是從1到循環31(實際上是幾天),而下面的循環默認值設置爲0。 (在現實中值是什麼計數)

for (int i = 1; i <= 31; i++) 
      { 
       thisList.Add(new KeyValuePair<int, int>(i, 0)); 
      } 

別的地方我使用這個列表來存儲值在DataTable行。

雖然這適用於DataTable中的第一行,但當添加一行時,thisList中的值將被彙總而不是替換。我在這裏使用這個循環爲:

DataTable table; 
//columns set somewhere here... not the issue in focus 
foreach(var value in aBigListOfThings) 
{ 
    for (int i = 0; i < thisList.Count(); i++) 
    { 

     if (condition) 
     { 
       int sumtemp = 0; 
       int.TryParse(someVariable.FirstOrDefault().someValue, out temp); 
       temp += thisList[i].Value; 
       // ====Possibly the issue 
       thisList[i] = new KeyValuePair<int, int>(unrelatedValue, sumtemp);        
       //=====                   
      } 
    } 

    //==== attempt the reset the value in the keyvaluepair to 0 


if (someothercondition) 
    { 
     for (int i = 1; i <= 31; i++) 
     { 
       thisList[i] = new KeyValuePair<int, int>(i, 0); 
     } 
    } 
} 

之前我加入了修復重置價值爲0(if (someothercondition)),該數據是這樣的:

1 | 2 | 3 | 4 | 5 | ...... 31 <---key 
------------------------------ 
2 | 4 | 6 | 8 | 10 | ...... n <---value 
3 | 7 | 11 | 15 | 19 | ...... n <---value 

雖然它應該是這樣的

1 | 2 | 3 | 4 | 5 | ...... 31 <---key 
------------------------------ 
2 | 4 | 6 | 8 | 10 | ...... n <---value 
1 | 3 | 5 | 7 | 9 | ...... n <---value 

我的理解,並四處尋找解決方案,KeyValuePair是不可改變的,如果有什麼不能被添加(如在+=,但可以更換.. (請糾正我,如果我錯了)

當我使用fix(wayyyy上面),我得到一個索引超出範圍異常。 Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index我採取意味着thisList[i] = new KeyValuePair<int, int>(i, 0);增加了更多的列表,而不是替換現有..

...如果你還在通過這個閱讀..我的問題是 一)爲什麼KeyValuePair說是彙總值時不可變? b)我如何簡單地將keyvaluepair中的值替換爲0而沒有?或者可能嗎?

任何幫助將在這一點真的很有用..已經破壞了我的頭一陣子。 :|

回答

1

List<T>起始指數爲0,而不是1這意味着您的最後一個循環需要是這樣的:通過30

for (int i = 0; i < 31; i++) 
{ 
    thisList[i] = new KeyValuePair<int, int>(i, 0); 
} 

這將替換在索引0的31個KeyValuePair小號順便說一句,爲什麼你沒有像前一個那樣創建循環,這是工作?

+0

或只是設置i = 1 ...... – Seabizkit

+0

完全忽略了這個!索引失敗或範圍異常的罪魁禍首!謝謝! :)它現在有效 – Tsar

+1

@Tsar另一種方式,而不是改變'thisList [i] .Value;'到'thisList [i + 1] .Value;'' –

0

爲什麼你不明白它並設置值?例如。

Dictionary<string, int> list = new Dictionary<string, int>(); 
list["test"] = 1; 
list["test"] += 1; 
Console.WriteLine (list["test"]); // will print 2