更好的收集或更好的方式在字典中搜索

时间:2017-05-24 08:16:31

标签: c#

我需要存储2个密钥(truefalse)及其对应的值(12)。

Dictionary<bool, int> X = new Dictionary<bool, int>();
X.Add(true, 1);
X.Add(false, 2);

还有其他更好的集合只有2个键值对吗?

然后对于其中一个外部值bool为true或false,我需要查找该键的值

int x = GetIntFromDictionary(X, true);

private static int GetIntFromDictionary(Dictionary<bool, int> dict, bool val)
{
    int v = 0;
    if (dict.ContainsKey(val))
    {
        v = dict[val];
    }

    return v;
}

如果合适,在字典或其他集合中查找值的最佳方法是什么?

4 个答案:

答案 0 :(得分:2)

由于val不可为空,并且您声明您的“词典”只包含2个键,因此您不需要任何集合,只需设置三元组或if语句

private static int GetValue(bool val)
{
    return val ? 1 : 2;
}

答案 1 :(得分:1)

您可以使用TryGetValue

private static int GetValue(Dictionary<bool, int> dict, bool val)
{
    int value;
    dict.TryGetValue(val, out value);

    return value;
}

如果存在则返回相关值,否则返回0。

如果0是合法值,请使用方法bool返回值

private static int GetValue(Dictionary<bool, int> dict, bool val)
{
    int value;
    if (dict.TryGetValue(val, out value))
    {
        return value;
    }

    return int.MinValue; // or any other indication
}

答案 2 :(得分:1)

如果将true / false映射到外部值是你的问题,那么我会做类似的事情。

var mapping = new int[] { externalValueFalse, externalValueTrue};

private static int GetValue(bool val)
{
  return mapping[val ? 1 : 0];
}

答案 3 :(得分:0)

bool类型的键的可能性为truefalse;这就是ContainsKeyTryGetValue ...

中没有必要的原因
    Dictionary<bool, int> X = new Dictionary<bool, int>() {
      {true, 5},
      {false, -15},
    };

    Dictionary<bool, int> OtherX = new Dictionary<bool, int>() {
      {true, 123},
      {false, 456},
    };


    ...

    private static int GetIntFromDictionary(Dictionary<bool, int> dict, bool val) {
      return dict[val];
    }    

    ...

    int result1 = GetIntFromDictionary(X, true);
    int result2 = GetIntFromDictionary(X, false);
    int result3 = GetIntFromDictionary(OtherX, true);
    int result4 = GetIntFromDictionary(OtherX, false);
相关问题