Nikhil Chavan
Nikhil Chavan

Reputation: 1715

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

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

Upvotes: 9

Views: 9465

Answers (6)

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

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.

Upvotes: 13

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

Enumerating a collection and modifying the same is not supported in Dictionary If you want to do that you can use ConcurrentDictionary which will be a overkill for this, since you're using single thread.

Try this.

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

Upvotes: 1

Rik
Rik

Reputation: 29243

You can't modify a collection in a while it's being enumerated in a foreach loop. this is because it could lead to some unexpected behavior.

Use a regular for loop instead.

Upvotes: 0

oleksii
oleksii

Reputation: 35925

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

Upvotes: 4

Steven Wood
Steven Wood

Reputation: 2785

Its because you are modifying the for each collection

foreach (var kvp in tempSortOrders)

tempSortOrders[kvp.Key] = null;

Upvotes: 1

Pankaj
Pankaj

Reputation: 2754

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

Upvotes: 1

Related Questions