What's the best way to set all values in a C# Dictionary?
Here is what I am doing now, but I'm sure there is a better/cleaner way to do this:
Dictionary<string,bool> dict = GetDictionary(); var keys = dict.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { dict[keys[i]] = false; }
I have tried some other ways with foreach, but I had errors.
Storing Data in Arrays. Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.
Use the spread syntax to push multiple values to an array, e.g. arr = [... arr, 'b', 'c', 'd']; . The spread syntax can be used to unpack the values of the original array followed by one or more additional values. Copied!
That is a reasonable approach, although I would prefer:
foreach (var key in dict.Keys.ToList()) { dict[key] = false; }
The call to ToList()
makes this work, since it's pulling out and (temporarily) saving the list of keys, so the iteration works.
A one-line solution:
dict = dict.ToDictionary(p => p.Key, p => false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With