atualização hashtable por outro hashtable?
-
10-07-2019 - |
Pergunta
Como posso atualizar os valores de uma tabela hash por outro hashtable,
Se segunda hashtable contém novas chaves, em seguida, eles devem ser adicionados a 1 mais deve atualizar o valor do 1º hashtable.
Solução
foreach (DictionaryEntry item in second)
{
first[item.Key] = item.Value;
}
Se necessário você poderia rolar isso em um método de extensão (supondo que você está usando .NET 3.5 ou mais recente).
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;
}
}
}
Outras dicas
Alguns código em que (com base no dicionário):
foreach (KeyValuePair<String, String> pair in hashtable2)
{
if (hashtable1.ContainsKey(pair.Key))
{
hashtable1[pair.Key] = pair.Value;
}
else
{
hashtable1.Add(pair.Key, pair.Value);
}
}
Eu tenho certeza que há uma solução mais elegante usando LINQ (embora, código I em 2,0;)).
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow