我可以确保在C#中的字典中只有一个特定的值吗?关于字典
例如,如果我定义一个字符串,其中的键是char并且value是char,那么我可以确保如果字符'a'已经是一个现有值,那么在字符'a'中不会有另一个值'a'字典?
我有一个解决方案,但我想知道如果有一个更好的:
static void Main()
{
Dictionary<int, int> dic = new Dictionary<int, int>();
bool valExists = false;
Console.WriteLine("please enter key and value");
int key = int.Parse(Console.ReadLine());
int val = int.Parse(Console.ReadLine());
foreach (KeyValuePair<int,int> keyval in dic)
{
if (keyval.Value == val)
{
valExists = true;
break;
}
}
if (!valExists)
dic.Add(key, val);
}
可能您应该使用该值作为密钥? http://stackoverflow.com/questions/9438060/c-sharp-dictionary-type-with-unique-keys-and-values可能有帮助吗? – Siva