在 C# 中按键获取字典值
在本教程中,我们将讨论如何通过 C# 中的键获取字典的值。
在 C# 中使用 []
方法通过键获取字典值
可以使用 Dictionary<T1,T2>
类在 C# 中声明字典。字典是一种数据结构,在 C# 中以键-值
对的形式保存数据。我们可以通过在 C# 中使用带有 []
方法的键来获取字典中的值。
using System;
using System.Collections.Generic;
namespace get_dictionary_value
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> mydictionary = new Dictionary<string, string>();
mydictionary.Add("Key 1", "Value 1");
mydictionary.Add("Key 2", "Value 2");
mydictionary.Add("Key 3", "Value 3");
Console.WriteLine(mydictionary["Key 3"]);
}
}
}
输出:
Value 3
我们使用 Dictionary<string, string>
类创建了一个字典 mydictionary
。之后,我们使用 []
方法在 mydictionary
中检索 Key 3
键的值。这种方法的唯一缺陷是,如果在字典中找不到键,则会引发异常。
使用 C# 中的 TryGetKey()
函数通过键获取字典值
TryGetKey()
函数检查是否键是否存在于字典中。TryGetKey()
函数返回一个布尔值。如果字典中存在键,则该函数返回 true
并将 out
参数的值更改为字典中键的值。如果字典中不存在该键,则该函数返回 false
。如果字典中不存在键,则 TryGetKey()
函数会处理 []
方法中引发的异常。以下代码示例向我们展示了如何使用 C# 中的 TryGetkey()
函数通过键在字典中获取值。
using System;
using System.Collections.Generic;
namespace get_dictionary_value
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> mydictionary = new Dictionary<string, string>();
mydictionary.Add("Key 1", "Value 1");
mydictionary.Add("Key 2", "Value 2");
mydictionary.Add("Key 3", "Value 3");
string value;
bool hasValue = mydictionary.TryGetValue("Key 3", out value);
if (hasValue)
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("Key not present");
}
}
}
}
输出:
Value 3
我们首先检查键是否存在于 mydictionary
字典中。如果存在,我们将检索该值并进行打印。如果没有,我们将打印 Key not present
。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。