How do I fetch the individual values...
You have some options:
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");
}
}
}
Per the docs, this method is more efficient if the program frequently tries keys that don't exist.
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");
}
}
}
This is the least efficient method.
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);
}
}
}
You could also use the indexer property without the try/catch block, but since your code doesn't enumerate the dictionary, it could throw an exception, so I don't recommend it.
This leads us to...
4. Enumerate the dictionary and use the indexer.
Enumeration could return the keys in any order, which you may or may not want.
foreach (KeyValuePair<(int, int), string> kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key.Item1} {kvp.Key.Item2}, Value: {kvp.Value}");
}