8

I am getting System.InvalidOperationException: Collection was modified; enumeration operation may not execute. error in my following code.

//temporary var for storing column sort orders according to view type
        Dictionary<string, bool?> tempColumnSortOrders=new Dictionary<string,bool?>(4);
 //Check for column name in col list
        if (tempColumnSortOrders.ContainsKey(fieldToSort))
        {
            //If exists set column sort order to new sort order
            //Set new sort order
            tempColumnSortOrders[fieldToSort] = sortOrder;
            var tempSortOrders = tempColumnSortOrders;
            //remove sort order of other columns
            foreach (var kvp in tempSortOrders)
            {
                //Reset other columns sort other than current column sort
                if (kvp.Key != fieldToSort)
                {
                    tempSortOrders[kvp.Key] = null;
                }
            }
            //Return name of column to sort
            return fieldToSort;
        }

Stack Trace

[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +52 System.Collections.Generic.Enumerator.MoveNext() +44 GlaziersCenter.Handlers.GetSiteViews.getColumnToSort(Int32 viewType) in d:\Projects\GlaziersCenter\GlaziersCenter\Handlers\GetSiteViews.ashx.cs:184 GlaziersCenter.Handlers.GetSiteViews.ProcessRequest(HttpContext context) in d:\Projects\GlaziersCenter\GlaziersCenter\Handlers\GetSiteViews.ashx.cs:68 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

4

6 回答 6

10

试试这个代码,

List<string> keys = new List<string>(tempSortOrders.Keys);
foreach (var key in keys)
{
    //Reset other columns sort other than current column sort
    if (key != fieldToSort)
    {
        tempSortOrders[key] = null;
    }
}

更新,

将集合转换为列表将解决问题。

于 2013-09-16T12:16:55.620 回答
4

foreach循环不允许您迭代的集合发生突变。要更改集合,请使用for循环。

于 2013-09-16T12:17:36.387 回答
1

Dictionary如果您想这样做,则不支持枚举集合并ConcurrentDictionary对其进行修改,因为您使用的是单线程,因此您可以使用这将是过度杀伤力。

尝试这个。

foreach (var kvp in tempSortOrders.ToArray())<--Note ToArray here
{
    //Reset other columns sort other than current column sort
    if (kvp.Key != fieldToSort)
    {
        tempSortOrders[kvp.Key] = null;
    }
}
于 2013-09-16T12:19:27.060 回答
1

错误是因为在此循环中,您修改了字典 tempSortOrders..

foreach (var kvp in tempSortOrders)
        {
            //Reset other columns sort other than current column sort
            if (kvp.Key != fieldToSort)
            {
                tempSortOrders[kvp.Key] = null;
            }
        }
于 2013-09-16T12:16:06.390 回答
1

这是因为您正在为每个集合修改

foreach(tempSortOrders 中的 var kvp

tempSortOrders [kvp.Key] = null;

于 2013-09-16T12:16:19.583 回答
0

您不能在foreach循环中枚举集合的同时修改它。这是因为它可能导致一些意想不到的行为。

请改用常规for循环。

于 2013-09-16T12:15:58.960 回答