如何从包含值元组作为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);**
}
}
}

如何获取单个值。。。


您有一些选择:


1.使用ContainsKey方法

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");
}
}
}

2.使用TryGetValue方法

根据文档,如果程序经常尝试不存在的键,这种方法会更有效。

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");
}
}
}

3.使用索引器并捕获KeyNotFoundException

这是效率最低的方法。

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属性,但由于你的代码没有枚举字典,它可能会引发异常,所以我不建议这样做

这将引导我们…


4.枚举字典并使用索引器

枚举可以按任何顺序返回键,您可能需要也可能不需要。

foreach (KeyValuePair<(int, int), string> kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key.Item1} {kvp.Key.Item2}, Value: {kvp.Value}");
}

最新更新