Melanie
Melanie

Reputation: 1429

Use list entries as keys for dictionary

I have a

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

telling me all of the things I should find in some input data. I'd like to convert this into a

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

where the dictionary keys are the same as the list entries, and all the values are false. I'll then run over the data, and update the dictionary value when I find the elements.

This seems simple, but

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

doesn't work because of an error:

Cannot implicitly convert type Dictionary<bool, string> to Dictionary<string, bool>

Upvotes: 3

Views: 3616

Answers (2)

Habib
Habib

Reputation: 223257

You can use Enumerable.ToDictionary and specify false as the value.

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

The code you are using will give you Dictionary<bool,string>, if you look in the intellisense then:

enter image description here

and hence the error:

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

Upvotes: 5

manojlds
manojlds

Reputation: 301147

You want to do something like this:

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

The overload that you were using will create a Dictionary<bool, string>, with key being bool and value the string values from the list. ( And having bool as key will mean, you can have only two entries ;)

Also, you rarely need to specify the type parameters like <string, bool> to methods explcitly, as they can be inferred, and you can use var for variables, like done above.

Upvotes: 7

Related Questions