我正在使用C#,我有一个名为intervalRecordsPerObject的Dictionary<string, List<TimeInterval>>类型的字典。我需要反复翻阅字典。问题是:每次我遍历字典时,都会添加更多的KeyValuePairs。随着字典的增加,我也需要不断地迭代新条目。
首先,我这样做了:一个简单的foreach循环,它给了我一个InvalidOperationException语句
Collection was modified; enumeration operation may not execute.
我知道,如果字典在C#循环之前用ToList()来转换,那么它就不能以这种方式迭代。
我知道我可以将键复制到一个临时数组,使用简单的for循环和Count迭代字典,并且每当向字典中添加一个新条目时,也可以向数组添加相应的键。现在,问题是一个简单的数组不能动态增长,而且我事先不知道所需的大小是多少。
为了继续前进,我想我应该这么做:
List<string> keyList = new List<string>(intervalRecordsPerObject.Count);
intervalRecordsPerObject.Keys.CopyTo(keyList.ToArray(), 0);我也不能这么做。keyList当前为空,因此keyList.toArray()返回长度为0的数组,这将给出一个ArgumentException语句
Destination array is not long enough to copy all the items in the collection. Check array index and length.
我被卡住了!知道我还能做什么吗?谢谢你的帮助。
增加1:
字典存储特定对象存在的时间间隔。键是对象的ID。新条目可能会在每次迭代中被添加(最坏的情况),甚至可能不会添加一次。是否添加条目取决于几个条件(对象是否与其他间隔重叠,等等)。这将触发ID和相应的间隔列表中的更改,然后将其作为新条目添加到字典中。
发布于 2013-08-30 12:30:30
就像这样:
List<string> keys = dict.Keys.ToList();
for (int i = 0; i < keys.Count; i++)
{
var key = keys[i];
List<TimeInterval> value;
if (!dict.TryGetValue(key, out value))
{
continue;
}
dict.Add("NewKey", yourValue);
keys.Add("NewKey");
}这里的诀窍是按索引枚举List<T>!这样,即使添加了新元素,for (...)也会“捕获”它们。
其他可能的解决方案,使用临时Dictionary<,>
// The main dictionary
var dict = new Dictionary<string, List<TimeInterval>>();
// The temporary dictionary where new keys are added
var next = new Dictionary<string, List<TimeInterval>>();
// current will contain dict or the various instances of next
// (multiple new Dictionary<string, List<TimeInterval>>(); can
// be created)
var current = dict;
while (true)
{
foreach (var kv in current)
{
// if necessary
List<TimeInterval> value = null;
// We add items only to next, that will be processed
// in the next while (true) cycle
next.Add("NewKey", value);
}
if (next.Count == 0)
{
// Nothing was added in this cycle, we have finished
break;
}
foreach (var kv in next)
{
dict.Add(kv.Key, kv.Value);
}
current = next;
next = new Dictionary<string, List<TimeInterval>>();
}发布于 2013-08-30 12:38:28
您可以按位置而不是按内容访问Keys,并使用普通的For loop (允许添加/删除而不受任何限制)。
for (int i = 0; i < dict.Keys.Count; i++)
{
string curKey = dict.Keys.ElementAt(i);
TimeInterval curVal = dict.Values.ElementAt(i);
//TimeInterval curVal = dict[curKey];
//Can add or remove entries
}https://stackoverflow.com/questions/18532803
复制相似问题