在C#中返回字典值而不将其赋值给变量?

Ada*_*dam 0 c# dictionary

我想使用字典的值而不将其赋值给变量:

Dictionary<int, string> LayoutByID = new Dictionary<int, string>() {
    { 0, "foo"},
    { 1, "bar"}
    // ...
};
Run Code Online (Sandbox Code Playgroud)

我可以为例如在创建变量时打印值:

string b;
LayoutByID.TryGetValue(1,out b);
print("Trying Dictionary to retrieve value for 1: " + b);
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更简单的方法,例如:

print("Trying Dictionary to retrieve value for 1: " + LayoutByID.TryGetValue(1 [???]));
Run Code Online (Sandbox Code Playgroud)

我知道我可以编写一个带有开关的函数,它的工作方式类似,但是使用Dictionaries可能会更便宜,因为我有一个更长的列表.谢谢你的建议!

Bas*_*ede 6

您可以使用Dictionary密钥访问,var x = LayoutByID[0];但如果Dictionary不包含具有该密钥的条目,您将获得异常.

为了避免抛出异常,您可以先使用LayoutByID.ContainsKey()- 检查密钥是否存在- 然后为这些情况编写逻辑:

if (LayoutByID.ContainsKey(0)) // Check if the key exists (replace 0 with whatever)
{
    var x = LayoutByID[0]; // Access the value and do whatever with it
    // ...
}
else
{
    // Key doesn't exist:
    // Do something else
}
Run Code Online (Sandbox Code Playgroud)

或者使用C#6.0,你也可以这样打印

var key = -1;
var myString = string.Empty;
LayoutByID.TryGetValue(key, out myString);
Console.WriteLine($"Trying Dictionary to retrieve value for {key}: {myString ?? "Error: Invalid ID"}");
Run Code Online (Sandbox Code Playgroud)