开发者

update hashtable by another hashtable?

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

if second hashtable c开发者_Python百科ontains 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 ;) ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜