Mel*_*nie 3 .net c# linq dictionary list
我有一个
List<string> myList = new List<string>();
Run Code Online (Sandbox Code Playgroud)
告诉我在一些输入数据中应该找到的所有内容.我想把它变成一个
Dictionary<string, bool> myDict = Dictionary<string, bool>();
Run Code Online (Sandbox Code Playgroud)
字典键与列表条目相同,所有值均为false.然后,我将遍历数据,并在找到元素时更新字典值.
这似乎很简单,但是
Dictionary<string, bool> myDict = myList.ToDictionary<string, bool>(x => false);
Run Code Online (Sandbox Code Playgroud)
由于错误而无效:
无法隐式转换
Dictionary<bool, string>为Dictionary<string, bool>
你想做这样的事情:
var dict = myList.ToDictionary(s => s, s => false);
Run Code Online (Sandbox Code Playgroud)
您正在使用的重载将创建一个Dictionary<bool, string>,键为bool并从列表中为值字符串值.(并且将bool作为键意味着,您只能有两个条目;)
此外,您很少需要指定类型参数,例如<string, bool>explcitly方法,因为它们可以推断,并且您可以使用var变量,如上所述.
您可以使用Enumerable.ToDictionary并将false指定为值.
myDict = myList.ToDictionary(r=> r, r=> false);
Run Code Online (Sandbox Code Playgroud)
Dictionary<bool,string>如果您查看intellisense,您正在使用的代码会给您:

因此错误:
无法将类型'System.Collections.Generic.Dictionary'隐式转换为'System.Collections.Generic.Dictionary'