2012-06-08 77 views
8
var rm = new ResourceManager(sometype); 

var resourceSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 

我想將上述資源集轉換爲字典。目前我正在通過循環手動完成,如下所示。使用linq將資源集轉換爲字典

var resourceDictionary = new Dictionary<string, string>(); 

foreach (var r in resourceSet) 
{ 
    var dicEntry = (DictionaryEntry)r; 
    resourceDictionary.Add(dicEntry.Key.ToString(), dicEntry.Value.ToString());   
} 

我該如何做到這一點很容易使用LINQ?

回答

29

嘗試這種情況:

var resourceDictionary = resourceSet.Cast<DictionaryEntry>() 
            .ToDictionary(r => r.Key.ToString(), 
                r => r.Value.ToString()); 
+1

完全忘記這個'鑄<>()'方法的! – superjos

2
var resourceDictionary = resourceSet.Select(r => (DictionaryEntry) r) 
            .ToDictionary(dicEntry => dicEntry.Key.ToString(), 
               dicEntry => dicEntry.Value.ToString());