.NET 幫助

C# 字典 Trygetvalue(它對開發者的運作方式)

C# 是一種多功能且強大的語言,提供了許多功能。 其中之一是 C# 字典。

理解 C# 字典的基礎知識

在深入了解 TryGetValue 方法之前,首先理解 C# 中的 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}
}
$vbLabelText   $csharpLabel

字典中的鍵是唯一的。 你可以通過訪問鍵來獲取對應的值,使得字典在查找功能上非常高效。

傳統方法:ContainsKey 方法

在處理 C# 字典時,一個常見的任務是獲取與特定鍵相關聯的值。 然而,直接訪問不存在的鍵可能會拋出一個 KeyNotFoundException,中斷程式的執行流程。 為了避免這種情況,一般做法是檢查指定的鍵是否存在於字典中。 這就是ContainsKey方法發揮作用的地方。

ContainsKey 方法是一個直接且簡明的函數,用來檢查特定鍵是否存在於字典中。 以下是 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)
$vbLabelText   $csharpLabel

它將鍵作為參數並返回布林值。 如果鍵存在於字典中,它將返回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}
}
$vbLabelText   $csharpLabel

現在,如果您想獲取名為 "Alice" 的學生的年齡,您首先需要使用ContainsKey方法來檢查 "Alice" 是否在 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.");
}
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
$vbLabelText   $csharpLabel

在這種情況下,程式會輸出 "Alice is 20 years old." 如果您嘗試獲取不在字典中的學生年齡,ContainsKey 方法將防止拋出 KeyNotFoundException,而是輸出一條訊息,表示該學生不存在。

然而,儘管ContainsKey方法可能很有用,但它並不總是最有效率的。 在上面的程式碼片段中,對該字典執行了兩次查找操作:一次是使用ContainsKey 方法,另一次是用來檢索值。 這可能會很耗時,尤其是在處理大型字典時。

雖然ContainsKey方法是一種簡單直觀的方式來處理字典中找不到指定鍵時的例外情況,但值得考慮替代方法如TryGetValue,它可以以更好的性能實現類似的功能。 我們將在接下來的部分更詳細地討論TryGetValue

結合驗證和檢索使用TryGetValue

這就是TryGetValue方法派上用場的地方。 TryGetValue 方法將驗證和取值結合在一步驟中,提供幾乎相同的代碼功能,但具有更高的性能。

TryGetValue 方法需要兩個參數:

  1. 您正在尋找的鑰匙。

  2. 一個 out 參數,如果鍵存在,則將保留其值。

    以下是語法:

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)
$vbLabelText   $csharpLabel

out 關鍵字用於表示此方法將改變 value 參數。 如果未找到指定的鍵,則out值將為該值類型的默認值(整數為0,引用類型為null)。 否則,它會持有對應所提供鍵的值。

以下是如何使用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
$vbLabelText   $csharpLabel

此代碼提供的功能幾乎與ContainsKey方法範例相同,但由於它只查找一次鍵,因此效率更高。

TryGetValue 使用範例

為了更好地了解TryGetValue方法,讓我們探討一個實用的代碼範例。 考慮一個學校資料庫,其中每個學生都有唯一的身份證號和相應的名字。 這些資料儲存在一個字典裡,以學生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"}
}
$vbLabelText   $csharpLabel

在這種情況下,假設您想要檢索ID為2的學生姓名,但您也想確保該ID的學生存在於資料庫中。

傳統上,您可能會先使用ContainsKey方法來檢查鍵(學生 ID 2)是否存在,然後訪問Dictionary以獲取相應的值(學生姓名)。 但是,使用TryGetValue方法,您可以在一步中完成此操作。

TryGetValue 方法需要兩個參數:您要查找的鍵,以及一個 out 參數,該參數將保存該鍵關聯的值(如果存在的話)。 如果找到鍵,該方法將返回true,並將相應的值分配給out參數。 如果不是,則會返回false,並且out參數將取其類型的預設值。

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
$vbLabelText   $csharpLabel

在這種情況下,TryGetValue 方法會在 studentNames 字典中尋找鍵 2。 如果找到該鍵,它會將相應的值(學生的名字)賦值給value變量,並且該方法返回true。 然後,程式會印出,「ID 為 2 的學生姓名是 Bob。」

如果TryGetValue方法找不到鍵2,它會將字串的預設值(即null)賦給value變量,並且該方法將返回false。 然後,代碼進入else塊,印出「字典中不存在 ID 為 2 的學生。」

TryGetValue通過將鍵存在檢查和值檢索合併為一步操作來簡化您的代碼。此外,它通過消除多次鍵查找操作,特別是在較大的字典中,提高了性能。

推出Iron Suite

隨著您在 C# 領域中的持續進步,您會發現有許多工具和庫可以顯著增強您的程式設計能力。 在這些工具中,Iron 函式庫是一套專為擴展 C# 應用程式功能而設計的工具。 它們包括IronPDF、IronXL、IronOCR和IronBarcode。 每個這些庫都有一套獨特的功能,並且在與標準 C# 結合使用時,它們都提供了顯著的優勢。

IronPDF

C# Dictionary `TryGetValue`(開發者指南運作原理)圖 1

探索 IronPDF 用於 PDF 創建在 .NET 中 是一個 C# 庫,旨在在 .NET 應用程序中從 HTML 創建 PDF 文件、編輯和提取 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
$vbLabelText   $csharpLabel

在我們的主題背景下,想像一個場景,你正在從一個字典中檢索學生數據,並希望生成一份 PDF 報告。 TryGetValue可以高效地獲取必要的數據,然後利用IronPDF創建PDF文檔。

IronXL

C# 字典 `TryGetValue`(開發人員如何使用)圖2

探索 IronXL for Excel Interactions 是一個用於 C# 和 .NET 的 Excel 庫。 它使開發人員能夠在 .NET 應用程序中讀取、寫入和創建 Excel 文件,而不需要 Interop。這對於需要從 Excel 試算表導出或導入數據的情況非常完美。

關於TryGetValue,假設您有一個字典,其中鍵代表產品ID,值代表其數量。 您可以使用TryGetValue來檢索特定產品的數量,然後使用IronXL更新Excel庫存管理電子表格中的該數量。

IronOCR

C# 字典 `TryGetValue`(開發人員指南)圖 3

釋放 IronOCR 的文字識別力量 是一款先進的光學字符識別(OCR)和條碼讀取程式庫,適用於 .NET 和 C#。 它允許開發人員在 .NET 應用程式中從圖像和 PDF 讀取文字和條碼。 當您需要從掃描文件或圖像中提取數據並在代碼中使用時,這將特別有用。

考慮一個使用 IronOCR 從掃描文件中提取學生證號碼的情景。 處理後,您將 ID 和相應的學生資料存儲在字典中。 在檢索特定學生的詳細資料時,可以使用TryGetValue從字典中高效地獲取數據。

IronBarcode

C# 字典 `TryGetValue`(開發者如何使用)圖 4

了解 IronBarcode 的條碼解決方案 是一個用於 .NET 的條碼讀取和寫入庫。 使用IronBarcode,開發人員可以生成和讀取各種條形碼和QR碼格式。 這是用於以緊湊、機器可讀格式編碼和解碼數據的強大工具。

在實際情境中,想像你在零售系統中使用條形碼來儲存產品信息。 每個條碼可以對應於儲存在字典中的唯一產品 ID。 當條碼被掃描時,您可以使用TryGetValue快速從字典中獲取並顯示相關的產品詳細資訊。

結論

在我們探討 Iron 程式庫與標準 C# 功能(如 TryGetValue 方法)的功能時,很明顯這些工具能夠顯著提升您的開發過程。 無論您是處理PDF、Excel檔案、OCR還是條碼,Iron Suite 都提供符合您需求的解決方案。

更誘人的是,每個產品都提供Iron Software 產品的免費試用,讓您可以免費探索和試驗功能。如果您決定繼續使用這些庫,則每個產品的許可證起價為$749。 然而,如果您對多個 Iron 程式庫感興趣,您可以購買完整的 Iron Suite,只需兩個單獨產品的價格。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 預設參數(開發者如何運作)
下一個 >
C# 圓桌會議(開發人員的運作方式)