Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to set all values in a C# Dictionary<string,bool>?

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.

like image 513
Ronnie Overby Avatar asked Jul 22 '09 17:07

Ronnie Overby


People also ask

How do you store all the values in an array?

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.

How do you set all values in an array to zero?

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.

How do you set multiple values in an array?

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!


2 Answers

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.

like image 72
Reed Copsey Avatar answered Oct 08 '22 21:10

Reed Copsey


A one-line solution:

dict = dict.ToDictionary(p => p.Key, p => false); 
like image 39
jeatsy Avatar answered Oct 08 '22 23:10

jeatsy