How do I extract a value out of a dictionary that contains a value tuple as the key in C#?

525 Views Asked by At

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);**
        }
    }
}
1

There are 1 best solutions below

0
On

How do I fetch the individual values...


You have some options:


1. Use the ContainsKey method.

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. Use the TryGetValue method.

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


3. Use the indexer and catch the KeyNotFoundException.

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