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>
source to share
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.
source to share
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:
and hence the error:
Cannot implicitly convert type 'System.Collections.Generic.Dictionary' to 'System.Collections.Generic.Dictionary'
source to share