2013-02-11 69 views
3

键我有一个使用列表条目作为字典

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

告诉我所有的事情,我应该在一些输入数据找到。我想将其转换为

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

其中字典键与列表条目相同,并且所有值都是false。然后我会遍历数据,并在找到元素时更新字典值。

这看似简单,但

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

不会因为一个错误的工作:

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

+0

“不起作用”=>虽然专家清楚问题是什么,但问题肯定会包括实际的错误。 – siride 2013-02-11 04:26:50

+0

siride - 的确如此,谢谢。 – Melanie 2013-02-11 04:34:00

+1

downvotes可能是因为短语“它不起作用”没有进一步的信息。你已经解决了这个问题,但人们可能没有回来删除他们的提议。 – siride 2013-02-11 14:07:37

回答

5

你想干什么像这样:

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

您正在使用的重载将创建一个Dictionary<bool, string>,键是bool并且从列表中为字符串赋值。 (具有布尔为重点将意味着,你只能有两个条目;)

而且,你很少需要explcitly指定类型的参数,如<string, bool>的方法,因为他们可以推断,您可以使用var变量,就像上面做的那样。

5

您可以使用Enumerable.ToDictionary并指定false作为值。

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

您正在使用的代码会给你Dictionary<bool,string>,如果你的智能感知看起来那么:

enter image description here

,因此错误:

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

+0

请记下* actual *问题,而不是仅仅倾销代码。 – siride 2013-02-11 04:27:10

+0

@siride,“不起作用”是指什么? - 这是应该**工作** – Habib 2013-02-11 04:28:45

+0

的答案中的代码,但问题是OP没有使用正确的重载来设置键和值,这应该解释。 – siride 2013-02-11 04:31:58