如何通过另一个哈希表
更新一个哈希表的值如果第二个哈希表包含新密钥,则必须将它们添加到第一个哈希表中,否则应更新第一个哈希表的值。
答案 0 :(得分:16)
foreach (DictionaryEntry item in second)
{
first[item.Key] = item.Value;
}
如果需要,您可以将其转换为扩展方法(假设您使用的是.NET 3.5或更高版本)。
Hashtable one = GetHashtableFromSomewhere();
Hashtable two = GetAnotherHashtableFromSomewhere();
one.UpdateWith(two);
// ...
public static class HashtableExtensions
{
public static void UpdateWith(this Hashtable first, Hashtable second)
{
foreach (DictionaryEntry item in second)
{
first[item.Key] = item.Value;
}
}
}
答案 1 :(得分:0)
一些代码(基于字典):
foreach (KeyValuePair<String, String> pair in hashtable2)
{
if (hashtable1.ContainsKey(pair.Key))
{
hashtable1[pair.Key] = pair.Value;
}
else
{
hashtable1.Add(pair.Key, pair.Value);
}
}
我确信使用LINQ有更优雅的解决方案(不过,我的代码是2.0;))。