如何从包含值元组作为C#中的键的字典中提取值?

问题描述

下面的代码片段初始化了一个以值元组为键的Dictionary。初始化后如何获取单个值?

static void Main(string[] args)
{
    Dictionary<(int,int),string> dict = new Dictionary<(int,string>();

    dict.Add((0,0),"nul,nul");

    dict.Add((0,1),et");

    dict.Add((1,"et,nul");

    dict.Add((1,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方法。

对于docs,如果程序经常尝试不存在的键,则此方法会更有效。

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

这是least efficient方法。

for (int row = 0; row <= 1; row++)
{
    for (int col = 0; col <= 1; col++)
    {
        try
        {
            Console.WriteLine($"Key: {row} {col},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}");
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...