Question

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.

Was it helpful?

Solution

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;
        }
    }
}

OTHER TIPS

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 ;) ).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top