[英]How do I extract a value out of a dictionary that contains a value tuple as the key in C#?
下面的代碼片段用一個值元組作為鍵初始化一個Dictionary
。 初始化后如何獲取單個值?
static void Main(string[] args)
{
Dictionary<(int, int), string> dict = new Dictionary<(int, int), string>();
dict.Add((0, 0), "nul,nul");
dict.Add((0, 1), "nul,et");
dict.Add((1, 0), "et,nul");
dict.Add((1, 1), "et,et");
for (int row = 0; row <= 1; row++)
{
for (int col = 0; col <= 1; col++)
{
Console.WriteLine("Key: {0}, Value: {1}",
**......Key,
......Value);**
}
}
}
我如何獲取單個值...
你有一些選擇:
for (int row = 0; row <= 1; row++)
{
for (int col = 0; col <= 1; col++)
{
if (dict.ContainsKey((row, col)))
{
Console.WriteLine($"Key: {row} {col}, Value: {dict[(row, col)]}");
}
else // key doesn't exist
{
Console.WriteLine($"Key: {row} {col} doesn't exist");
}
}
}
根據docs ,如果程序經常嘗試不存在的鍵,則此方法更有效。
for (int row = 0; row <= 1; row++)
{
for (int col = 0; col <= 1; col++)
{
if (dict.TryGetValue((row, col), out string value))
{
Console.WriteLine($"Key: {row} {col}, Value: {value}");
}
else // key doesn't exist
{
Console.WriteLine($"Key: {row} {col} doesn't exist");
}
}
}
這是效率最低的方法。
for (int row = 0; row <= 1; row++)
{
for (int col = 0; col <= 1; col++)
{
try
{
Console.WriteLine($"Key: {row} {col}, Value: {dict[(row, col)]}");
}
catch (KeyNotFoundException ex)
{
Console.WriteLine($"dict does not contain key {row} {col}");
Console.WriteLine(ex.Message);
}
}
}
您也可以在沒有 try/catch 塊的情況下使用 indexer 屬性,但由於您的代碼不枚舉字典,因此可能會引發異常,因此我不推薦它。
這導致我們...
枚舉可以以任何順序返回鍵,您可能想要也可能不想要。
foreach (KeyValuePair<(int, int), string> kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key.Item1} {kvp.Key.Item2}, Value: {kvp.Value}");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.