2013-03-28 48 views
1

問題:更好的辦法來OrderedDictionary轉換爲詞典<字符串,字符串>

如何從OrderedDictionary轉換爲Dictionary<string, string>以簡潔,但性能方法?

現狀:

我有,我不能碰那個希望我傳遞一個Dictionary<string, string>一個lib。不過,我想建立一個OrderedDictionary,因爲訂單在我的代碼中非常重要。所以,我正在與OrderedDictionary合作,當它需要時,我需要將它轉換爲Dictionary<string, string>

我迄今爲止嘗試:

var dict = new Dictionary<string, string>(); 
var enumerator = MyOrderedDictionary.GetEnumerator(); 
while (enumerator.MoveNext()) 
{ 
    dict.Add(enumerator.Key as string, enumerator.Value as string); 
} 

我們有了提升的空間在這裏。是否有更簡潔的方式來執行此轉換?任何性能考慮?

如果使用的是通用的,而不是SortedDictionary<TKey, TValue>我使用.NET 4

回答

5

只是對您的代碼進行了兩項改進。首先,你可以使用foreach而不是while,這會隱藏GetEnumerator的細節。其次,您可以預先分配目標字典中的所需空間,因爲您知道要複製的項目數量。

using System.Collections.Specialized; 
using System.Collections.Generic; 
using System.Collections; 

class App 
{ 
    static void Main() 
    { 
    var myOrderedDictionary = new OrderedDictionary(); 
    myOrderedDictionary["A"] = "1"; 
    myOrderedDictionary["B"] = "2"; 
    myOrderedDictionary["C"] = "3"; 
    var dict = new Dictionary<string, string>(myOrderedDictionary.Count); 
    foreach(DictionaryEntry kvp in myOrderedDictionary) 
    {  
     dict.Add(kvp.Key as string, kvp.Value as string); 
    } 
    } 

} 

使用LINQ,轉換就地字典,如果你想字典的新實例 ,而不是填充一些現有的一個替代做法:

using System.Linq; 
... 
var dict = myOrderedDictionary.Cast<DictionaryEntry>() 
.ToDictionary(k => (string)k.Key, v=> (string)v.Value); 
+0

感謝您的回答。我嘗試了'foreach',但是不知道如何獲得'.Key'和'.Value',但是我使用'var kvp'而不是'DictionaryEntry kvp'。現在看起來不錯。我也喜歡linq方法。 – lbstr

1

,你可以簡單地使用Dictionary<TKey, TValue>構造函數的參數IDictionary<TKey, TValue>

var dictionary = new Dictionary<string, string>(MyOrderedDictionary); 

注:你會而不是能夠使用相同的類來維護訂單並從Dictionary派生,因爲Dictionary中的方法不是虛擬的。圖書館的創建者應該在公開曝光的圖書館方法中使用IDictionary而不是Dictionary,但他們現在不需要處理它。

+0

感謝您的回答。我確實看到了帶有'SortedDictionary'的字典的構造函數。我只是不確定在我的情況下鍵是否有問題。至少它保證了訂單。這可能是我走的路線。另外,非常感謝你對圖書館的失望。這是一個不幸的情況。 – lbstr

相關問題