我需要用相应的值(true和2)存储2键(1和2)。
Dictionary<bool, int> X = new Dictionary<bool, int>();
X.Add(true, 1);
X.Add(false, 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;
}如果合适的话,在字典或其他集合中查找值的最佳方法是什么?
发布于 2017-05-24 08:50:31
类型为的的可能性是true和false,这就是为什么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);发布于 2017-05-24 08:19:55
由于val不可空,而且您的“字典”只包含两个键,所以您不需要任何集合,只需设置一个三元或if语句
private static int GetValue(bool val)
{
return val ? 1 : 2;
}发布于 2017-05-24 08:31:02
您可以使用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
}https://stackoverflow.com/questions/44152751
复制相似问题