The below code snippet initializes a Dictionary
with a value tuple as key. How do I fetch the individual values after initializing?
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);**
}
}
}
You have some options:
1. Use the ContainsKey method.
2. Use the TryGetValue method.
Per the docs, this method is more efficient if the program frequently tries keys that don't exist.
3. Use the indexer and catch the KeyNotFoundException.
This is the least efficient method.
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.