簡體   English   中英

用另一個哈希表更新哈希表?

[英]update hashtable by another hashtable?

如何通過另一個哈希表更新一個哈希表的值,

如果第二個哈希表包含新密鑰,則必須將它們添加到第一個哈希表,否則應更新第一個哈希表的值。

foreach (DictionaryEntry item in second)
{
    first[item.Key] = item.Value;
}

如果需要,您可以將其轉換為擴展方法(假設您使用的是.NET 3.5或更高版本)。

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

一些代碼(基於字典):

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

我確信使用LINQ有一個更優雅的解決方案(不過,我的代碼是2.0;))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM