C# – Dictionary error – Collection was modified; enumeration operation may not execute

cnet

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

Best Answer

Try this code instead,

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;
    }
}

Update,

Converting the collection to list will be solve the issue.

Related Topic