如何通过另一个哈希表更新一个哈希表的值,
如果第二个哈希表包含新的键,则必须将它们添加到第一个哈希表中,否则应该更新第一个哈希表的值。
如何通过另一个哈希表更新一个哈希表的值,
如果第二个哈希表包含新的键,则必须将它们添加到第一个哈希表中,否则应该更新第一个哈希表的值。
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;
}
}
}
基于字典的一些代码:
foreach (KeyValuePair<String, String> pair in hashtable2)
{
if (hashtable1.ContainsKey(pair.Key))
{
hashtable1[pair.Key] = pair.Value;
}
else
{
hashtable1.Add(pair.Key, pair.Value);
}
}