我工作的事,我需要從數據庫中獲得一些價值觀和成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而沒有?或者可能嗎?
任何幫助將在這一點真的很有用..已經破壞了我的頭一陣子。 :|
或只是設置i = 1 ...... – Seabizkit
完全忽略了這個!索引失敗或範圍異常的罪魁禍首!謝謝! :)它現在有效 – Tsar
@Tsar另一種方式,而不是改變'thisList [i] .Value;'到'thisList [i + 1] .Value;'' –