views:

210

answers:

2

How can I update the values of one hashtable by another hashtable,

if second hashtable contains new keys then they must be added to 1st else should update the value of 1st hashtable.

A: 

Some code on that (based on Dictionary):

        foreach (KeyValuePair<String, String> pair in hashtable2)
        {
            if (hashtable1.ContainsKey(pair.Key))
            {
                hashtable1[pair.Key] = pair.Value;
            }
            else
            {
                hashtable1.Add(pair.Key, pair.Value);
            }
        }

I'm sure there's a more elegant solution using LINQ (though, I code in 2.0 ;) ).

Bobby
This doesn't compile. Is it meant to be real C# or just pseudocode?
LukeH
@Luke: Thank you, I really should start coding in C# if I give answers on such questions...
Bobby
It compiles fine now and works correctly for `Dictionary<K,V>`, but it won't work for `Hashtable`.
LukeH
+8  A: 
foreach (DictionaryEntry item in second)
{
    first[item.Key] = item.Value;
}

If required you could roll this into an extension method (assuming that you're using .NET 3.5 or newer).

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;
        }
    }
}
LukeH
This doesn't capture one of the requirements "if second hashtable contains new keys then they must be added to 1st", and will most likely throw an exception
ParmesanCodice
@ParmesanCodice: It meets that requirement *exactly*. Why don't you try it and see for yourself? From the MSDN documentation: "You can also use the Item property to add new elements by setting the value of a key that does not exist in the Hashtable... However, if the specified key already exists in the Hashtable, setting the Item property overwrites the old value." http://msdn.microsoft.com/en-us/library/system.collections.hashtable.item.aspx
LukeH
@Luke, my apologies I was not aware of this behavior.
ParmesanCodice
It would be great if C# has a feature like hashtable1.Update(hashTable2); :-)or like Hashtable.Update(h1, h2);
Tumbleweed
@shahjapan: You can easily make your own extension method to do this. I'll update the answer...
LukeH