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);**
}
}
}
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...
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}");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.