2016-03-02 53 views
0

在進行同行代碼審查時,我觀察到我的同事編寫了一個循環遍歷字典並具有各種開關情況的代碼,其中一種情況是他通過字典獲取其他值。請參閱以下代碼片段迭代字典對象時所通過的詞典:需要的建議

foreach (KeyValuePair<string, string> kvp in dictionary_Object) 
{ 
    switch (kvp.Key) 
    { 
    case "Name": 
    { 
     string ipconnection = GetIPConnectionName(dictionary_Object); 
     //Do something with ipconnection 
    } 
    break; 

    case "TCPIPPort": 
     //Do something 
     break; 

    case "TCPIPAddress": 
     //Do something 
     break; 

    case "DefaultProViewNXGAddress": 
     //Do something 
     break; 

    // Setting values of the Timeout parameters 
    case "Comms_TimeOut": 
    case "Comms_Retries": 
    case "FW_File_Retries": 
     Another_Dictionary[kvp.Key] = kvp.Value; 
     break; 
    } 
} 

有沒有更好的方法來即興創建。

+1

什麼是代碼的問題?你可以從改善身份開始。 – nnunes10

+1

此問題屬於http://codereview.stackexchange.com –

+0

可能您需要使用http://codereview.stackexchange.com/ – Valentin

回答

1

不是相反遍歷整個字典,然後通過過濾switch我會傾向於定義一個擴展方法來選擇性地執行一些基於給定鍵的代碼。畢竟,鑰匙只能找到一次。

這裏的擴展方法:

public static bool IfContainsKeyThenExecute<K, V>(
    this Dictionary<K, V> dictionary, K key, Action<K, V> action) 
{ 
    V value; 
    var found = dictionary.TryGetValue(key, out value); 
    if (found) 
    { 
     action(key, value); 
    } 
    return found; 
} 

然後代碼如下所示:

dictionary_Object.IfContainsKeyThenExecute("Name", (k, v) => 
{ 
    string ipconnection = GetIPConnectionName(dictionary_Object); 
    //Do something with ipconnection 
}); 

dictionary_Object.IfContainsKeyThenExecute("TCPIPPort", (k, v) => { /* Do Something */ }); 
dictionary_Object.IfContainsKeyThenExecute("TCPIPAddress", (k, v) => { /* Do Something */ }); 
dictionary_Object.IfContainsKeyThenExecute("DefaultProViewNXGAddress", (k, v) => { /* Do Something */ }); 

dictionary_Object.IfContainsKeyThenExecute("Comms_TimeOut", (k, v) => Another_Dictionary[k] = v); 
dictionary_Object.IfContainsKeyThenExecute("Comms_Retries", (k, v) => Another_Dictionary[k] = v); 
dictionary_Object.IfContainsKeyThenExecute("FW_File_Retries", (k, v) => Another_Dictionary[k] = v); 
+0

謝謝,這似乎是一個好建議 –

+0

我不能投票的答案,因爲點數的聲譽。 :( –

0

它相當簡單的預過濾器的字典基礎上有名字,然後執行代碼上正確的字典

var nameDict = dictionary_Object.Where(x => x.Key == "name").ToDictionary(k => k.Key); 

//do your operations on the filtered dictionary etc... 
string ipconnection = GetIPConnectionName(nameDict);