如何通过一个哈希表更新另一个哈希表的值,
如果第二个哈希表包含新的关键字,则必须将它们添加到第一个哈希表中,否则应更新第一个哈希表的值。
发布于 2009-11-30 22:07:25
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;
}
}
}发布于 2009-11-30 22:07:04
上面的一些代码(基于字典):
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编写代码;) )。
https://stackoverflow.com/questions/1820017
复制相似问题