Is it safe to remove from SortedList during iteration

My question is: is it safe to list the removal of an element from a SortedList?

SortedList<decimal, string> myDictionary;
// omitted code

IEnumerator<decimal, string> enum = myDictionary.GetEnumerator();

while(enum.MoveNext)
{
  // is it ok to remove here?
  myDictionary.Remove(enum.Current.Key);
}
+3
source share
6 answers

This will throw an exception - you cannot modify the collection, iterate over it.

If you think about it a little, you will understand why. If adding or removing from the collection was allowed, you will no longer iterate over the same collection - you have too many (add) or not enough elements (delete).

+8
source

, , . , , . foreach, while, , .

var removeList = new List<decimal>();
foreach (var item in myDictionary)
{
    // have a condition which indicates which items are to be removed
    if (item.Key > 1)
    {
        removeList.Add(item.Key);
    }
}

, , LINQ

var removeList = myDictionary.Where(pair => pair.Key > 1).Select(k => k.Key).ToList();

.

// remove from the main collection
foreach (var key in removeList)
{
    myDictionary.Remove(key);
}
+4

. - , , .

, .

+2

. InvalidOperationExcpetion. , , . :

SortedList , , . , .

+2

, . , SortedList, RemoveAt.

, , O (n), . O (n ^ 2) O (n ^ 2 * log (n)). RemoveAt - O (n), . Remove O (log (n)), RemoveAt. , , , , , "n".

var myDictionary = new SortedList<decimal, string>();

// omitted code

int i = 0;
while (myDictionary.Count > 0 && i < myDictionary.Count)
{
  if (/* predicate to use for removal */)
  {
    myDictionary.RemoveAt(i);
  }
  else
  {
    i++;
  }
}
+2

:

            int counter= MyDictionary.Count;
            if (counter == 0)
                return;

            for (int i = 0;  i < counter;i++)
            {
                KeyValuePair<MyIdentifier, MyValue> key = (KeyValuePair<MyIdentifier, MyValue>)MyDictionary.ToArray()[i];
                MyIdentifier identifier = null;

                if (key.Key != null)
                    identifier = key.Key as MyIdentifier;

                if (identifier != null)
                    if (MyCondition)
                    {
                        MyDictionary.Remove(identifier);
                        counter--;
                    }
            }
0

Source: https://habr.com/ru/post/1742454/


All Articles