actualizar tabla hash por otra tabla hash?
-
10-07-2019 - |
Pregunta
¿Cómo puedo actualizar los valores de una tabla hash por otra tabla hash?
si la segunda tabla hash contiene nuevas claves, entonces deben agregarse a la 1.ª parte, debe actualizar el valor de la 1.a tabla hash.
Solución
foreach (DictionaryEntry item in second)
{
first[item.Key] = item.Value;
}
Si es necesario, puede incluir esto en un método de extensión (suponiendo que esté utilizando .NET 3.5 o más reciente).
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;
}
}
}
Otros consejos
Algún código sobre eso (basado en el Diccionario):
foreach (KeyValuePair<String, String> pair in hashtable2)
{
if (hashtable1.ContainsKey(pair.Key))
{
hashtable1[pair.Key] = pair.Value;
}
else
{
hashtable1.Add(pair.Key, pair.Value);
}
}
Estoy seguro de que hay una solución más elegante usando LINQ (aunque codifico en 2.0;)).
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow