C# 字典 Trygetvalue(開發者的工作原理)
C# 是一種多才且強大的語言,提供許多功能。 其中一個是 C# 的 Dictionary。
了解 C# Dictionary的基礎知識
在深入了解 TryGetValue 方法之前,了解Dictionary 在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}
}
Dictionary中的鍵是唯一的。 您可以存取鍵以獲取對應的值,這使得Dictionary在查找功能方面非常高效。
傳統方法:ContainsKey 方法
在使用C# Dictionary時,一個常見的任務是獲取與特定鍵相關的值。 然而,直接存取不存在的鍵可能會拋出KeyNotFoundException,中斷您的程式流程。 為避免這種情況,常見做法是檢查指定的鍵是否存在於Dictionary中。 這就是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)
它將鍵作為參數並返回一個布林值。 如果鍵在Dictionary中,它將返回true; 如果沒有,將返回false。
請考慮以下範例,其中有一個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}
}
現在,如果您想獲得名為" 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
在這種情況下,程式將列印" Alice is 20 years old." 。如果您嘗試獲取不在Dictionary中的學生的年齡,KeyNotFoundException,而是列印一條學生不存在的消息。
然而,雖然ContainsKey 方法可能很有用,但由於對Dictionary執行兩次查找操作:一次是ContainsKey 方法,然後一次是為了獲取值,因此效率不總是最高的。 這可能會很耗時,尤其是在處理大型Dictionary時。
雖然TryGetValue,它可以在提高效能的同時實現類似功能。 我們將在以下各節中更詳細地討論TryGetValue。
使用TryGetValue結合驗證與檢索
這時候TryGetValue方法就派上用場了。 TryGetValue 方法在單步中結合了驗證和值檢索,提供幾乎相同的程式碼功能但具有更高效的效能。
TryGetValue方法需要兩個參數:
- 您正在尋找的鍵。
- 一個外部參數,如果鍵存在,它將保存其值。
這裡是語法:
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)
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
該程式碼提供的功能幾乎與ContainsKey 方法範例相同,但更有效率,因為它只查找一次鍵。
TryGetValue 實踐中的範例程式碼
為了更好地理解TryGetValue方法,我們來探索一個實際的程式碼範例。 考慮一個學校資料庫,其中每個學生都有一個唯一的ID和對應的名字。 這些資料儲存在一個以學生ID作為鍵,名字作為值的Dictionary中。
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"}
}
在這種情況下,假設您想檢索ID為2的學生的名字,但您也想確保該ID的學生存在於資料庫中。
傳統上,您可能會先使用ContainsKey方法檢查鍵(學生ID2)是否存在,然後存取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
在這種情況下,TryGetValue 方法在studentNamesDictionary中查找鍵2。 如果它找到鍵,它會將對應的值分配給true。 然後,程式會列印出" ID為2的學生名字是Bob。"。
如果TryGetValue 方法未找到鍵2,它將為一個字串(即null)分配預設值給value 變數,然後該方法將返回false。 程式碼然後進入else區塊,列印出"在字典中不存在ID為2的學生。"。
TryGetValue通過將鍵存在確認和值檢索結合到一個步驟中來簡化您的程式碼。此外,通過消除多次鍵查找操作的需要,它在更大Dictionary中特別提升了效能。
介紹Iron Suite
隨著您在C#旅程中不斷進步,您將發現提供給您的許多工具和程式庫可以大大增強您的程式設計能力。 其中包括Iron 程式庫,一套專門設計用於擴展C# 應用程式的工具。 它們包括IronPDF、IronXL、IronOCR 和IronBarcode。 這些程式庫中的每一個都有其獨特的功能集合,並且當與標準C#結合使用時,它們都提供了顯著的優勢。
IronPDF

探索IronPDF生成.NET中的PDF是一個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
在我們的話題中,想像一種情況,您從Dictionary中檢索學生資料,並希望生成PDF報告。 TryGetValue可以有效地獲取所需的数据,並然後利用IronPDF建立PDF文件。
IronXL

探索IronXL 進行 Excel 互動是一個用於C#和.NET的Excel程式庫。 它使開發人員能夠在.NET應用程式中讀取、編寫和建立Excel文件而無需使用Interop。這是需要從Excel電子表格導出或導入資料的情境的理想方案。
關於TryGetValue,假設您有一個Dictionary,鍵代表產品ID,值代表其數量。 您可以使用TryGetValue來檢索特定產品的數量,然後使用IronXL來更新Excel庫存管理電子表格中的數量。
IronOCR

釋放IronOCR的文字識別能力 是一個用於.NET和C#的高級OCR(光學字元識別)和條碼讀取程式庫。 它允許開發人員在.NET應用程式中從影像和PDF中讀取文字和條碼。 當您需要從掃描文件或影像中提取資料並在程式中使用時,這特別有用。
設想一個場景,您使用IronOCR從掃描檔中提取學生ID。 處理後,您將ID和對應的學生資訊儲存在Dictionary中。 在檢索特定學生的資料時,TryGetValue可以用來高效地從Dictionary中獲取資料。
IronBarcode

了解IronBarcode 條碼解決方案是一個用於.NET的條碼讀取和寫入程式庫。 使用IronBarcode,開發人員可以生成和讀取各種條碼和QR碼格式。 它是一個強大的工具,用於以緊湊的機器可讀格式編碼和解碼資料。
在實際情況下,想像您正在使用條碼儲存零售系統中的產品資訊。 每個條碼可以對應到作為鍵的唯一產品ID,並儲存在Dictionary中。 當掃描一個條碼時,您可以使用TryGetValue 快速從Dictionary中檢索和顯示相關的產品資料。
結論
正如我們在探討Iron 程式庫與標準C#功能(如TryGetValue 方法)的功能時所顯示的那樣,這些工具可以顯著提高您的開發過程。 無論您是在處理PDF、Excel文件、OCR還是條碼,Iron Suite都有符合您需求的解決方案。
更吸引人的是,每個這些產品都提供Iron Software產品的免費試用,讓您可以免費探索和試驗這些功能。如果您決定繼續使用這些程式庫,授權以$999開頭。 但是,如果您對多個Iron 程式庫有興趣,可以以僅相當於兩個個別產品的價格購買整個Iron Suite,從而獲得更多價值。
常見問題
TryGetValue方法如何提升在C#應用程式中的效能?
TryGetValue方法透過將關鍵字驗證與值檢索合併為一個操作來提升效能。這減少了多次查詢的需求,特別是在處理大型資料集時提高效能。
C#中的ContainsKey和TryGetValue方法有何不同?
ContainsKey檢查詞典中是否存在某個鍵而不檢索其值,而TryGetValue在一個步驟中檢查鍵的存在並檢索其值,使其更具效率。
Iron程式庫可以與C# Dictionary操作整合嗎?
可以,Iron程式庫如IronPDF,IronXL,IronOCR和IronBarcode可與C# Dictionary操作整合以增強應用程式。例如,在使用IronPDF生成動態報告時,TryGetValue可以用於有效地管理資料。
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和Barcode功能工具,增強了開發者在C#應用程式中有效處理多種任務的能力。




