I want to use the value of a dictionary without assigning it to a variable:
Dictionary<int, string> LayoutByID = new Dictionary<int, string>() {
{ 0, "foo"},
{ 1, "bar"}
// ...
};
I can for e.g. print the values if I create a variable:
string b;
LayoutByID.TryGetValue(1,out b);
print("Trying Dictionary to retrieve value for 1: " + b);
But I was wondering if there is a simpler way, something like:
print("Trying Dictionary to retrieve value for 1: " + LayoutByID.TryGetValue(1 [???]));
I understand I could write a function with a switch in it that would work similarly, but using Dictionaries might be cheaper as I have a longer list. Thanks for advice!
You can access the Dictionary
with the key like var x = LayoutByID[0];
But you will get an exception, if the Dictionary
does not contain an entry with that key.
In order to avoid an exception being throw, you can first check if the key exists using LayoutByID.ContainsKey()
- and then write your logic for those cases:
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
}
or with C# 6.0 you could also print like this
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"}");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments