Use dictionary key entries

I have

List<string> myList = new List<string>();

      

telling me everything I have to find in some input. I would like to convert this to

Dictionary<string, bool> myDict = Dictionary<string, bool>();

      

where the dictionary keys are the same as the entries in the list and all values ​​are false. Then I fired up the data and updated the dictionary value when I find the items.

It seems simple, but

Dictionary<string, bool> myDict = myList.ToDictionary<string, bool>(x => false);

      

does not work due to error:

Cannot implicitly convert type Dictionary<bool, string>

toDictionary<string, bool>

+3


source to share


2 answers


You want to do something like this:

var dict = myList.ToDictionary(s => s, s => false);

      



The overload you used will create Dictionary<bool, string>

with a bool key and a string value from the list. (And with bool as a key, you can only have two entries;)

Also, you rarely need to specify type parameters, such as <string, bool>

, for methods, how they can be inferred, and you can use var

for variables as above.

+5


source


You can use Enumerable.ToDictionary and supply false as value.

myDict  = myList.ToDictionary(r=> r, r=> false);

      

The code you are using will give you Dictionary<bool,string>

if you look in intellisense and then:



enter image description here

and hence the error:

Cannot implicitly convert type 'System.Collections.Generic.Dictionary' to 'System.Collections.Generic.Dictionary'

+5


source







All Articles