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>toDictionary<string, bool>
You want to do something like this:
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 usevarfor variables, like done above.