There is a collection, type

Dictionary<String, int> 

At some point, it is necessary to remove the first X elements from it. (More precisely, there is a cycle that works with the first X elements, after which they should be thrown out of the collection)

How can I do that? As far as I know, elements can be deleted from Dictionary only separately (Remove) or all together (Clear). There’s nothing like List.RemoveAll (statement) for Dictionary. It was thought to delete the elements right after working with them in a loop:

  foreach (KeyValuePair<string, int> item in items) { // что-то делаем items.Remove(item.Key); } 

But, in my opinion, deleting items from the collection right along the cycle for it is a bad idea.

  • Brilliantly the same)). @ShockWave, envelope in response, or something. I will accept. Something became suspicious of me to often go crazy on simple things. - Olter
  • Don't chase rating, take away for nothing :) - ShockWave
  • By the way, a spell on simple things is a sign of processing, or the fact that you spend less than 2 hours a day programming - ShockWave
  • 2
    @Olter - I note that the phrase "first X elements" for IDictionary<T, U> is a hellish tin. Not only can IDictionary<,> not guarantee the same order for two different foreach launches (which is generally an exception rather than a rule), but also any addition of an element to IDictionary<,> can change the traversal order of this collection. - It is clear that, in connection with the above, the phrase "first X elements" seems rather strange. - Costantino Rupert
  • one
    @ Kotik_hochet_kushat - the author has indicated that the first X elements go in the context of the current for-each iteration. Its logical-syntactic error is perceived by you in the style of the program itself. The process of writing this program, hell, is hardcore catastrophically different from the process of its execution. Thank. - ShockWave

2 answers 2

Create a list of keys, and delete in the next cycle.

    Do not use foreach, use for:

     for(int i=0; i < items.length; i++){ if(условие){ //удаляем... i--; //делаем шаг назад так как количество элементов уменьшилось } } 
    • I would like to see an example of the "conditions" for this approach. - Costantino Rupert