我可以確保在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