首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在不断增长的字典中迭代

在不断增长的字典中迭代
EN

Stack Overflow用户
提问于 2013-08-30 12:21:05
回答 2查看 1.6K关注 0票数 2

我正在使用C#,我有一个名为intervalRecordsPerObjectDictionary<string, List<TimeInterval>>类型的字典。我需要反复翻阅字典。问题是:每次我遍历字典时,都会添加更多的KeyValuePairs。随着字典的增加,我也需要不断地迭代新条目。

首先,我这样做了:一个简单的foreach循环,它给了我一个InvalidOperationException语句

Collection was modified; enumeration operation may not execute.

我知道,如果字典在C#循环之前用ToList()来转换,那么它就不能以这种方式迭代。

我知道我可以将键复制到一个临时数组,使用简单的for循环和Count迭代字典,并且每当向字典中添加一个新条目时,也可以向数组添加相应的键。现在,问题是一个简单的数组不能动态增长,而且我事先不知道所需的大小是多少。

为了继续前进,我想我应该这么做:

代码语言:javascript
复制
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和相应的间隔列表中的更改,然后将其作为新条目添加到字典中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-30 12:30:30

就像这样:

代码语言:javascript
复制
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<,>

代码语言:javascript
复制
// 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>>();
}
票数 1
EN

Stack Overflow用户

发布于 2013-08-30 12:38:28

您可以按位置而不是按内容访问Keys,并使用普通的For loop (允许添加/删除而不受任何限制)。

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18532803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档