[英]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.