收藏被修改。枚举操作可能无法执行

时间:2014-03-13 17:28:27

标签: c#

Dictionary<string, lim> urlsLimited = new Dictionary<string, lim>();
struct lim
{
    public int min;
    public int max;
}


foreach (KeyValuePair<string, lim> pair in urlsLimited)
{
    if (urlsLimited[pair.Key].min < urlsLimited[pair.Key].max)
    {
        string like = od.LikeDiscussions(pair.Key);
        if (like == "Like")
        {
            lock (locker)
            {
                good_like++;
                lim val = pair.Value;
                val.min++;
                urlsLimited[pair.Key] = val;
                log_good_like(good_like);
            }
        }
     }
}

在foreach的第一个循环之后,我收到了Collection。枚举操作可能无法执行。如何摆脱它?

2 个答案:

答案 0 :(得分:1)

由于您没有更改Keys,您可以试试这个:

foreach (var key in urlsLimited.Keys)
{
    if (urlsLimited[key].min < urlsLimited[key].max)
    {
        string like = od.LikeDiscussions(key);
        if (like == "Like")
        {
            lock (locker)
            {
                good_like++;
                lim val = pair.Value;
                val.min++;
                urlsLimited[key] = val;
                log_good_like(good_like);
            }
        }
     }
}

答案 1 :(得分:-1)

这将解决您的问题:
foreach (KeyValuePair pair in urlsLimited.ToArray())