我需要存储 2 个键(true
和 false
)及其相应的值(1
和 2
).
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;
}
如果合适,在字典或其他集合中查找值的最佳方法是什么?
最佳答案
由于 val
不可为空,并且您声明您的“字典”仅包含 2 个键,因此您不需要任何集合,只需设置一个三元或 if 语句
private static int GetValue(bool val)
{
return val ? 1 : 2;
}
关于c# - 更好的收藏或更好的字典搜索方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44152751/