.NET 帮助

C# 字典 TryGetValue(开发人员如何使用)

发布 2023年八月29日
分享:

C# 是一种功能强大的通用语言,可提供多种功能。其中包括 C# 词典。

了解 C# 词典的基础知识

在深入研究 TryGetValue 方法之前,了解 C# 中的 Dictionary 是什么至关重要。简单地说,字典是键/值对的集合。例如,您可能有一个 Dictionary,其中的键是学生的姓名 (字符串值),其值为相应的年龄 (整数值).


    Dictionary<string, int> studentAges = new Dictionary<string, int>
    {
        {"Alice", 20},
        {"Bob", 22},
        {"Charlie", 19}
    };

    Dictionary<string, int> studentAges = new Dictionary<string, int>
    {
        {"Alice", 20},
        {"Bob", 22},
        {"Charlie", 19}
    };
Dim studentAges As New Dictionary(Of String, Integer) From {
	{"Alice", 20},
	{"Bob", 22},
	{"Charlie", 19}
}
VB   C#

字典中的键是唯一的。您可以通过访问键值来获取相应的值,这使得字典的查找功能异常高效。

传统方法:ContainsKey方法

在使用 C# 字典时,常见的任务是获取与特定键相关的值。然而,直接访问不存在的键可能会抛出 "KeyNotFoundException"(键未找到异常),从而中断程序流程。为了避免这种情况,通常的做法是检查指定的键是否存在于字典中。这就是 ContainsKey 方法发挥作用的地方。

ContainsKey 方法是一个简单直观的函数,用于检查 Dictionary 中是否存在某个键。下面是 ContainsKey 方法的基本语法:

Dictionary<TKey, TValue>.ContainsKey(TKey key)
Dictionary<TKey, TValue>.ContainsKey(TKey key)
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Dictionary<TKey, TValue>.ContainsKey(TKey key)
VB   C#

它以键为参数,并返回一个布尔值。如果键在字典中,则返回 true;如果不在字典中,则返回 false

在下面的示例中,我们有一个以学生姓名为键、以学生年龄为值的字典。

Dictionary<string, int> studentAges = new Dictionary<string, int>
{
    {"Alice", 20},
    {"Bob", 22},
    {"Charlie", 19}
};
Dictionary<string, int> studentAges = new Dictionary<string, int>
{
    {"Alice", 20},
    {"Bob", 22},
    {"Charlie", 19}
};
Dim studentAges As New Dictionary(Of String, Integer) From {
	{"Alice", 20},
	{"Bob", 22},
	{"Charlie", 19}
}
VB   C#

现在,如果要获取名为 "Alice "的学生的年龄,首先要使用 ContainsKey 方法检查 "Alice "是否是字典中的一个键。

string student = "Alice";
if(studentAges.ContainsKey(student))
{
    int age = studentAges [student];
    Console.WriteLine($"{student} is {age} years old.");
}
else
{
    Console.WriteLine($"{student} does not exist in the dictionary.");
}
string student = "Alice";
if(studentAges.ContainsKey(student))
{
    int age = studentAges [student];
    Console.WriteLine($"{student} is {age} years old.");
}
else
{
    Console.WriteLine($"{student} does not exist in the dictionary.");
}
Dim student As String = "Alice"
If studentAges.ContainsKey(student) Then
	Dim age As Integer = studentAges (student)
	Console.WriteLine($"{student} is {age} years old.")
Else
	Console.WriteLine($"{student} does not exist in the dictionary.")
End If
VB   C#

在这种情况下,程序将打印 "Alice 今年 20 岁"。如果试图获取 Dictionary 中不存在的学生年龄,ContainsKey 方法会阻止抛出 KeyNotFoundException 异常,并打印出该学生不存在的信息。

不过,虽然 ContainsKey 方法很有用,但它并不总是最有效的方法。在上面的代码片段中,对 Dictionary 执行了两次查找操作:一次用于 ContainsKey 方法,另一次用于检索值。这可能会很耗时,尤其是在处理大型字典时。

虽然 ContainsKey 方法是一种简单直观的方法,可以在字典中找不到指定键时处理异常,但也值得考虑其他方法,如 TryGetValue,它可以实现类似的功能,而且性能更好。我们将在下面的章节中详细讨论 TryGetValue 方法。

将验证和检索与 TryGetValue 结合起来

这时,TryGetValue 方法就派上用场了。TryGetValue "方法将验证和值检索结合在一个步骤中,提供了几乎相同的代码功能,但性能更强。

TryGetValue "方法需要两个参数:

1.你要找的钥匙

2.一个输出参数,如果键存在,该参数将保存值。

语法如下

Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
VB   C#

out 关键字用于表示此方法将更改参数 value。如果找不到指定的键,out 值将是值类型的默认值。 (整数为 0,引用类型为空).否则,它将保存与所提供键值相对应的值。

下面介绍如何使用 TryGetValue

string student = "Alice";
if(studentAges.TryGetValue(student, out int age))
{
    Console.WriteLine($"{student} is {age} years old.");
}
else
{
    Console.WriteLine($"{student} does not exist in the dictionary.");
}
string student = "Alice";
if(studentAges.TryGetValue(student, out int age))
{
    Console.WriteLine($"{student} is {age} years old.");
}
else
{
    Console.WriteLine($"{student} does not exist in the dictionary.");
}
Dim student As String = "Alice"
Dim age As Integer
If studentAges.TryGetValue(student, age) Then
	Console.WriteLine($"{student} is {age} years old.")
Else
	Console.WriteLine($"{student} does not exist in the dictionary.")
End If
VB   C#

这段代码提供了与 ContainsKey 方法示例几乎相同的功能,但由于只查找一次键,因此效率更高。

TryGetValue 操作代码示例

为了更好地理解 TryGetValue 方法,让我们来看一个实际的代码示例。考虑一个学校数据库,其中每个学生都有一个唯一的 ID 和相应的姓名。这些数据存储在一个字典中,学生 ID 是键,姓名是值。

Dictionary<int, string> studentNames = new Dictionary<int, string>
{
    {1, "Alice"},
    {2, "Bob"},
    {3, "Charlie"}
};
Dictionary<int, string> studentNames = new Dictionary<int, string>
{
    {1, "Alice"},
    {2, "Bob"},
    {3, "Charlie"}
};
Dim studentNames As New Dictionary(Of Integer, String) From {
	{1, "Alice"},
	{2, "Bob"},
	{3, "Charlie"}
}
VB   C#

在这种情况下,假设您要检索 ID 为 2 的学生姓名,但同时也要确保数据库中存在这个 ID 的学生。

传统上,您可能首先使用 ContainsKey 方法来检查键是否存在于数据库中。 (学生编号 2) 然后访问字典以获取相应的值 (学生姓名).不过,使用 TryGetValue 方法,您只需一步就能实现这一目标。

TryGetValue方法需要两个参数:要查找的键和一个out参数,如果存在,该参数将保存与该键相关的值。如果键被找到,该方法将返回true,并将相应的值赋值给out参数。如果没有,则返回falseout`参数将使用其类型的默认值。

int i = 2; // Student ID
if (studentNames.TryGetValue(i, out string value))
{
    Console.WriteLine($"The name of the student with ID {i} is {value}.");
}
else
{
    Console.WriteLine($"No student with ID {i} exists in the dictionary.");
}
int i = 2; // Student ID
if (studentNames.TryGetValue(i, out string value))
{
    Console.WriteLine($"The name of the student with ID {i} is {value}.");
}
else
{
    Console.WriteLine($"No student with ID {i} exists in the dictionary.");
}
Dim i As Integer = 2 ' Student ID
Dim value As String
If studentNames.TryGetValue(i, value) Then
	Console.WriteLine($"The name of the student with ID {i} is {value}.")
Else
	Console.WriteLine($"No student with ID {i} exists in the dictionary.")
End If
VB   C#

在这种情况下,"TryGetValue "方法会在 "studentNames "字典中查找键 2。如果找到了键,就会把相应的值赋给 value 变量 (学生姓名)该方法返回 true。然后,程序会打印出 "ID 为 2 的学生姓名是 Bob"。

如果 TryGetValue 方法没有找到键 2,它将为字符串分配默认值 (为空) 变量,该方法将返回 false。然后代码进入 else 块,打印出 "字典中不存在 ID 为 2 的学生"。

TryGetValue` 将键存在性检查和值检索合并为一个步骤,从而简化了代码。此外,由于无需进行多次键查找操作,它还能提高性能,尤其是在字典较大的情况下。

钢铁套房介绍

随着您在 C# 的道路上不断前进,您会发现有许多工具和库可供您使用,它们可以大大提高您的编程能力。其中包括 Iron 库,这是一套专门用于扩展 C# 应用程序功能的工具。它们包括 IronPDF、IronXL、IronOCR 和 IronBarcode。每个库都有一套独特的功能,当与标准 C# 结合使用时,它们都能提供显著的优势。

IronPDF

C# 词典 `TryGetValue`(开发人员如何使用) 图 1

IronPDF 是一个 C# 库,旨在 从 HTML 创建 PDF 文件在 .NET 应用程序中编辑和提取 PDF 内容。使用 IronPDF,您可以以编程方式生成 PDF 报告、填写 PDF 表单和操作 PDF 文档。该库还提供 HTML 到 PDF 的转换功能,可轻松将现有的 HTML 内容转换为 PDF。

IronPDF 的亮点在于 HTML 转 PDF 功能,可保持所有布局和样式完好无损。它允许你从网页内容创建 PDF,适用于报告、发票和文档。HTML 文件、URL 和 HTML 字符串都可以无缝转换为 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

就我们的主题而言,想象一下从字典中获取学生数据并生成 PDF 报告的场景。TryGetValue "可以高效地获取必要的数据,然后利用 IronPDF 创建 PDF 文档。

IronXL

C# 词典 `TryGetValue`(开发人员如何使用) 图 2

IronXL 是一个用于 C# 和 .NET 的 Excel 库。它能让开发人员在.NET 应用程序中读取、写入和创建 Excel 文件,而无需 Interop。它非常适合需要从 Excel 电子表格中导出或导入数据的情况。

关于 TryGetValue,假设您有一个字典,其中键代表产品 ID,值代表产品数量。您可以使用 TryGetValue 来检索特定产品的数量,然后使用 IronXL 在 Excel 库存管理电子表格中更新该数量。

IronOCR

C# 词典 TryGetValue(开发人员如何使用) 图 3

IronOCR 是一种先进的 OCR (光学字符识别) 适用于 .NET 和 C# 的条形码读取库。它允许开发人员在 .NET 应用程序中读取图像和 PDF 中的文本和条形码。当您需要从扫描的文档或图像中提取数据并在代码中加以处理时,这一点尤其有用。

假设您使用 IronOCR 从扫描文档中提取学生 ID。处理完成后,您将 ID 和相应的学生详细信息存储在字典中。在检索某个学生的详细信息时,可以使用 TryGetValue 从字典中高效地获取数据。

IronBarcode

C# 词典 `TryGetValue`(开发人员如何使用) 图 4

IronBarcode 是一款适用于 .NET 的条形码读写库。通过 IronBarcode,开发人员可以生成和读取各种条形码和 QR 码格式。它是一款功能强大的工具,能以紧凑、机器可读的格式对数据进行编码和解码。

在实际应用中,想象一下在零售系统中使用条形码来存储产品信息。每个条形码都对应一个唯一的产品 ID,作为键存储在字典中。扫描条形码时,您可以使用 TryGetValue 快速从字典中获取并显示相关的产品详细信息。

结论

在我们结合标准 C# 功能(如 TryGetValue 方法)探索了 Iron 库的功能后,我们可以清楚地看到,这些工具可以显著增强您的开发流程。无论您是在处理 PDF、Excel 文件、OCR 还是条形码,Iron 库都能为您提供帮助。 铁套房 可根据您的需求量身定制解决方案。

更诱人的是,每种产品都能提供 免费试用,让您可以免费探索和尝试这些功能。如果您决定继续使用这些库,每个产品的许可证起价为 $749。不过,如果您对多个 Iron 库感兴趣,还可以发现更多价值,因为您只需以两个单个产品的价格即可购买完整的 Iron Suite。

< 前一页
C# 默认参数(开发人员工作原理)
下一步 >
C# 圆 (如何为开发人员工作)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >