2013-02-11 80 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