Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dictionary values to null

Tags:

c#

I'm wondering if there is a way to put all dictionary values to null (or each elements) ? Because we can't iterate on it if the values has been changed to null.

(I've searched on Stackoverflow before asking this simple question but I didn't find a clear response on this issue).

Regards

like image 922
NicoC Avatar asked Dec 21 '22 15:12

NicoC


1 Answers

Is this what you want?

foreach(var key in dict.Keys.ToList())
    dict[key] = null;

Important: The call to ToList(). This will copy the keys to a temporary list. Otherwise you would get an InvalidOperationException with the message:

Collection was modified; enumeration operation may not execute.

like image 179
Daniel Hilgarth Avatar answered Jan 08 '23 13:01

Daniel Hilgarth