简体   繁体   中英

update hashtable by another hashtable?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM