题
如何通过另一哈希表更新一个哈希表的值,
如果第二散列表包含新密钥则它们必须被添加到其他第一应该更新第一散列表的值。
解决方案
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);
}
}
我确信有使用LINQ(虽然,我在2.0代码;)更好的解决方案。)
不隶属于 StackOverflow