更好的集合或更好的字典搜索方式



我需要存储 2 个键(truefalse (及其相应的值(12 (。

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

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

然后对于其中一个外部值 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;
}

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

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

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

您可以使用 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
}

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

var mapping = new int[] { externalValueFalse, externalValueTrue};
private static int GetValue(bool val)
{
  return mapping[val ? 1 : 0];
}

bool 型键的唯一可能性是 truefalse ; 这就是为什么在ContainsKey中没有必要,TryGetValue...

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

最新更新