Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<string, bool?> error - Collection was modified; enumeration operation may not execute

Tags:

c#

.net

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

like image 517
Nikhil Chavan Avatar asked Sep 16 '13 12:09

Nikhil Chavan


3 Answers

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.

like image 69
Chamika Sandamal Avatar answered Sep 28 '22 03:09

Chamika Sandamal


foreach loop doesn't allow mutations of the collection you iterate on. To change a collection, use a for loop.

like image 21
oleksii Avatar answered Sep 28 '22 02:09

oleksii


The error is because in this loop, you have modified your dictionary tempSortOrders..

foreach (var kvp in tempSortOrders)
        {
            //Reset other columns sort other than current column sort
            if (kvp.Key != fieldToSort)
            {
                tempSortOrders[kvp.Key] = null;
            }
        }
like image 36
Pankaj Avatar answered Sep 28 '22 02:09

Pankaj