开发者

Check a Hashtables key/value pairs for a combination in C#?

I have a Hashtable, which contains values like this:

key: 123456 value: UV

key: 654321 value: HV

...

Now I want to check if a combination already exists and dont insert anything. So if my key is 123456 and my value i开发者_C百科s UV, no new entry is added. How could I do this?

Thanks :-)


A Hashtable (or, preferably, a Dictionary<TKey, TValue>) contains exactly one value for a stored key. So, if you add a new key-value-pair to the collection, you can simply check for the existence of the key before doing so:

static bool AddIfNotContainsKey<K,V>(this Dictionary<K,V> dict, K key, V value)
{
    if (!dict.ContainsKey(key))
    {
        dict.Add(key, value);
        return true;
    }
    return false;
}

Example:

var dict = new Dictionary<string, string>();

dict.AddIfNotContainsKey("123456", "UV");  // returns true
dict.AddIfNotContainsKey("654321", "HV");  // returns true

dict.AddIfNotContainsKey("123456", "??");  // returns false

string result = dict["123456"];           // result == "UV"


Use the Contains method of the Hashtable, and as @dtb says the Hashtable contains one value for a key, so in your case if you need to have things like ("key1","value1"), ("key1","value2") then maybe is more apropiate store the pair as the key making the existence of this values perfectly valid.


you could make a function with something like this, I have tried it and it is working.

class Program
{
    static void Main()
    {
    Dictionary<string, bool> d = new Dictionary<string, bool>();
    d.Add("cat", true);
    d.Add("dog", false);
    d.Add("sprout", true);

    // A.
   // We could use ContainsKey.
    if (d.ContainsKey("dog"))
    {
        // Will be 'False'
        bool result = d["dog"];
        Console.WriteLine(result);
    }

    // B.
    // Or we could use TryGetValue.
    bool value;
    if (d.TryGetValue("dog", out value))
    {
        // Will be 'False'
        bool result = value;
        Console.WriteLine(result);
    }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜