WDUK
WDUK

Reputation: 1524

Override value of existing key in hashtable in C#

I have a function that recieves a hashTable and i apply it to an already existing hashTable.

What I would like to do is replace or update a key's value in the hashTable when passed to the function. Here is an example of what i mean:

void UpdateHashTable(Hashtable ht){      
           userData.Add("myKey",5);
//replace matching keys from old value to the new ht values in argument 
}

void replacement(){
  Hashtable hashTable = new Hashtable;
            hashTable.Add("mykey",15);

  UpdateHashTable(hashTable);
}

Is there a built in replace function to do this or some way to check matching keys?

Upvotes: 1

Views: 3169

Answers (1)

binderbound
binderbound

Reputation: 799

I found your question a bit hard to understand, but assuming I understood correctly:

There isn't a built in copy that does the behaviour you are talking about, but it's very easy to implement.

steps: foreach keyvaluepair, check if the key exists, if it does, insert. otherwise, update existing.

void UpdateHashTable(Hashtable ht){
    foreach(var kvp in ht){
        if(userData.ContainsKey(kvp.Key)){
            userData[kvp.Key] = kvp.Value;
        }
        else{
            userData.Add(kvp.Key, kvp.Value);
        }
    }
}

example outcome:

ht [ 2 => "A", 3 => "B"]

userData [ 3 => "C", 4 => "D" ]

userData after updateHashTable [ 2=> "A", 3 =>"B", 4=>"D"]

Upvotes: 2

Related Questions