【问题标题】:Check a Hashtables key/value pairs for a combination in C#?在 C# 中检查 Hashtables 键/值对的组合?
【发布时间】:2011-07-12 15:02:39
【问题描述】:

我有一个哈希表,其中包含如下值:

键:123456 值:UV
键:654321 值:HV
...

现在我想检查一个组合是否已经存在并且不插入任何东西。因此,如果我的键是 123456 并且我的值是 UV,则不会添加新条目。我怎么能这样做?

谢谢:-)

【问题讨论】:

  • HashTable 类已弃用;不要使用它,而是使用通用的Dictionary 类(来自System.Collections.Generic)。

标签: c# hashtable


【解决方案1】:

Hashtable(或者,最好是Dictionary<TKey, TValue>)只包含一个存储键的值。因此,如果您向集合中添加一个新的键值对,您只需在执行此操作之前检查该键是否存在:

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

例子:

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"

【讨论】:

  • 这是迄今为止最好的答案:D
【解决方案2】:

使用 Hashtable 的 Contains 方法,正如@dtb 所说,Hashtable 包含一个键的值,所以在你的情况下,如果你需要像 ("key1","value1"), ("key1" ,"value2") 那么可能更合适的存储对作为键,使这个值的存在完全有效。

【讨论】:

    【解决方案3】:

    你可以用这样的东西来做一个函数,我试过了,它正在工作。

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

    【讨论】:

    • 我认为你的 try get 值会返回 true。
    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多