迭代字典对象时传递的字典:需要建议
本文关键字:字典 对象 迭代 | 更新日期: 2023-09-27 18:37:03
在进行同行代码审查时,我观察到我的同事编写了一个代码,该代码循环字典并具有各种开关情况,在其中一个情况下,他传递了字典以获取其他值。 请参阅以下代码片段
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;
}
}
有没有更好的方法来即兴创作。
与其遍历整个字典,然后按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);
它非常简单地根据名称预过滤字典,然后在正确的字典上执行代码
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);