2010-02-28 84 views
2

我很好奇,是否有一種方法可以在linq語句本身中捕獲較低的行(創建字典和循環以添加值)。現在select new返回一個新的匿名類型,但我想知道是否有一種方法可以使它返回一個預填充了所有值的Dictionary。我們可以使用linq更簡潔嗎?

XDocument reader = XDocument.Load("sl.config"); 
    var configValues = from s in reader.Descendants("add") select new { Key = s.Attribute("key").Value, s.Attribute("value").Value }; 

    Dictionary<string, string> Settings = new Dictionary<string, string>(); 

    foreach (var s in configValues) 
    { 
     Settings.Add(s.Key, s.Value); 
    } 

回答

6

嘗試Enumerable.ToDictionary擴展方法。

XDocument reader = XDocument.Load("sl.config"); 
var Settings = reader.Descendants("add") 
    .ToDictionary(s => s.Attribute("key").Value, s => s.Attribute("value").Value); 
+0

應當'詞典<字符串,字符串>設置='而不是'變種configValues =' – Gabe 2010-02-28 17:55:42

+0

是的,固定的變量名,感謝;-) – 2010-02-28 17:58:41

+0

感謝您的! – keithwarren7 2010-02-28 18:21:27

2
var = XDocument.Load("sl.config").Descendants("add").ToDictionary 
    (x => x.Attribute("key"). Value, x => x.Attribute("value"). Value); 
+0

我希望你不要介意我格式化了一下。 :) – 2010-02-28 18:17:15