跳過到頁腳內容
.NET幫助

C# 字典 Trygetvalue(開發者的工作原理)

C# 是一種多用途且功能強大的語言,可提供許多功能。 其中包括 C# 詞典。

瞭解 C# 辭典的基礎知識

在深入了解 TryGetValue 方法之前,了解 C# 中的字典是什麼至關重要。 簡單來說,字典是鍵/值對的集合。 例如,您可能有一個詞典,其中的鍵是學生的姓名(字串值),而值是他們相對應的年齡(整數值)。

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

詞典中的鍵是唯一的。 您可以存取鍵來取得相對應的值,這使得 Dictionaries 在查詢功能上有難以置信的效率。

傳統方法: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"是否是字典中的一個鍵。

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 20 歲"。如果您嘗試取得字典中不存在的學生的年齡,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 和相對應的姓名。 這些資料儲存在以學生 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)是否存在,然後存取字典以取得相應的值(學生姓名)。 但是,使用 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 library 是一套專門用來擴充 C# 應用程式功能的工具。 這些工具包括 IronPDF、IronXL、IronOCR 和 IronBarcode。 這些函式庫都有其獨特的功能,當與標準 C# 結合使用時,它們都能提供顯著的優勢。

IronPDF。

! C# 字典 TryGetValue(開發者使用方法)圖 1

Discover IronPDF for PDF Creation in .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

Explore IronXL for Excel Interactions 是適用於 C# 和 .NET 的 Excel 函式庫。 它可讓開發人員在 .NET 應用程式中讀取、寫入和建立 Excel 檔案,而無需 Interop。它非常適合需要從 Excel 試算表匯出或匯入資料的情況。

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

IronOCR。

! C# 字典 TryGetValue(開發者使用方法)圖 3

Unleash the Power of IronOCR for Text Recognition 是用於 .NET 和 C# 的先進 OCR(光學字元辨識)和 BarCode 閱讀函式庫。 它可讓開發人員在 .NET 應用程式中讀取影像和 PDF 中的文字和 BarCode。 當您需要從掃描的文件或影像中擷取資料,並在程式碼中處理時,這可能會特別有用。

考慮一個您使用 IronOCR 從掃描文件中擷取學生 ID 的情境。 處理完成後,您會將 ID 和對應的學生詳細資料儲存在辭典中。 在檢索特定學生的詳細資訊時,可以使用 TryGetValue 從字典中有效地獲取資料。

IronBarcode。

! C# 字典 TryGetValue(開發者使用方法)圖 4

Learn About IronBarcode for Barcode Solutions 是 .NET 的條碼读写庫。 透過 IronBarcode,開發人員可以產生和讀取各種條碼和 QR 代碼格式。 它是以精簡、機器可讀的格式對資料進行編碼和解碼的強大工具。

在實際的情境中,想像您在零售系統中使用 BarCode 儲存產品資訊。 每個 BarCode 都可以對應到一個獨特的產品 ID,並儲存為辭典中的關鍵字。 掃描條碼時,您可以使用 TryGetValue 從字典中快速取得並顯示相關的產品詳細資訊。

結論

當我們探索 Iron 庫的功能以及標準 C# 功能(例如 TryGetValue 方法)時,很明顯,這些工具可以顯著增強您的開發流程。 無論您是處理 PDF、Excel 檔案、OCR 或 BarCode,Iron Suite 都有為您量身打造的解決方案。

更吸引人的是,這些產品均提供Iron Software Products 的免費試用版,讓您可以免費探索和體驗各項功能。如果您決定繼續使用這些庫,則每個產品的許可證價格從 $999 起。 不過,如果您對多個 Iron 函式庫感興趣,還可以發現更多價值,因為您只需花兩個單獨產品的價格,就可以購買完整的 Iron Suite。

常見問題解答

TryGetValue 方法如何改善 C# 應用程式的性能?

TryGetValue 方法將鍵驗證和值檢索合併為一個操作,從而提高性能。這減少了多次查找的需求,提高了效率,尤其是在處理大型資料集時。

ContainsKey 和 TryGetValue 方法在 C# 中有何不同?

ContainsKey 檢查字典中是否存在鍵而不檢索其值,而 TryGetValue 在一個步驟中檢查鍵的存在並檢索其值,使其更為高效。

Iron 程式庫可以與 C# 字典操作整合嗎?

可以,像 IronPDF、IronXL、IronOCR 和 IronBarcode 這樣的 Iron 程式庫可以與 C# 字典操作整合以增強應用程式。例如,可使用 TryGetValue 來在使用 IronPDF 生成動態報告時有效管理資料。

IronPDF 如何改善 .NET 應用程式中的文件生成?

IronPDF 允許從 HTML 創建、編輯和轉換 PDF,保持文件的版面配置和樣式。它特別適用於在 .NET 應用程式中程式化生成報告、發票和其他文件。

在 C# 中使用 IronXL 進行試算表管理有哪些好處?

IronXL 提供了讀取、寫入和創建 Excel 文件的功能,而無需 Interop,這使得它非常適合 .NET 應用程式中的資料匯出和匯入任務。

IronOCR 如何促進 C# 應用程式中的資料提取?

IronOCR 能夠從圖像和 PDF 中提取文字和條碼,使其在處理掃描的文件和將提取的資料整合到 C# 應用程式時很有用。

IronBarcode 程式庫在 C# 開發中扮演著什麼角色?

IronBarcode 允許生成和讀取條碼和 QR 碼,提供了一種將資料編碼和解碼為機器可讀格式的方法,這對於庫存管理和 C# 中的其他應用程式非常重要。

為何開發人員應在 C# 專案中使用 Iron Suite?

Iron Suite 提供了一套全面的工具,用於 PDF、Excel、OCR 和條碼功能,使開發人員能夠在 C# 應用程式中有效處理各種任務。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我