[英]Setting Value in KeyValuePair to a default value
我正在做一些需要从数据库中获取一些值并放入DataTable. I have this a
事情DataTable. I have this a
DataTable. I have this a
声明DataTable. I have this a
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
是不可变的,如果不能添加任何内容(如+=
,但可以替换..(如果我错了,请纠正我))
当我使用修复程序时(上面的方式),我得到了索引超出范围的异常。 Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
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
。.我的问题是a)为什么说KeyValuePair
在聚合值时是不可变的? B)我怎么能简单地替换值keyvaluepair
为0没有? 还是可能吗?
此时,任何帮助都将非常有用。。 :|
List<T>
的起始索引为0,而不是1。这意味着最后一个循环需要如下所示:
for (int i = 0; i < 31; i++)
{
thisList[i] = new KeyValuePair<int, int>(i, 0);
}
这将替换索引0到30中的31个KeyValuePair
。
顺便说一句,为什么不以与上一个可行的循环相同的方式创建循环?
您为什么不直接获取并设置值呢? 例如。
Dictionary<string, int> list = new Dictionary<string, int>();
list["test"] = 1;
list["test"] += 1;
Console.WriteLine (list["test"]); // will print 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.