跳過到頁腳內容
.NET幫助

C# 查找功能(開發者的工作原理)

歡迎來到我們關於 C# 的實用函數 Find 的教學。 您剛剛發現了一個可以簡化編碼流程的強大功能。 因此,無論您是經驗豐富的程式設計師,還是剛開始工作,本教學都會帶您了解所有的要素,讓您輕鬆上手。

尋找的基礎知識

從本質上講,Find 是一個函數,它允許你查找集合、陣列或列表中滿足指定謂詞的第一個元素。 您會問什麼是謂詞? 在程式設計中,謂語是一種函數,用來測試針對集合中元素所定義的特定條件。

現在,讓我們深入一個公共類別的範例。

public class BikePart
{
    public string Id { get; set; } // Property to identify the bike part

    // Override the Equals method to specify how to compare two BikePart objects
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is BikePart))
            return false;

        return this.Id == ((BikePart)obj).Id;
    }

    // Override GetHashCode for hashing BikePart objects
    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    // Override ToString to return a custom string representation of the object
    public override string ToString()
    {
        return "BikePart ID: " + this.Id;
    }
}
public class BikePart
{
    public string Id { get; set; } // Property to identify the bike part

    // Override the Equals method to specify how to compare two BikePart objects
    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is BikePart))
            return false;

        return this.Id == ((BikePart)obj).Id;
    }

    // Override GetHashCode for hashing BikePart objects
    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    // Override ToString to return a custom string representation of the object
    public override string ToString()
    {
        return "BikePart ID: " + this.Id;
    }
}
Public Class BikePart
	Public Property Id() As String ' -  Property to identify the bike part

	' Override the Equals method to specify how to compare two BikePart objects
	Public Overrides Function Equals(ByVal obj As Object) As Boolean
		If obj Is Nothing OrElse Not (TypeOf obj Is BikePart) Then
			Return False
		End If

		Return Me.Id = DirectCast(obj, BikePart).Id
	End Function

	' Override GetHashCode for hashing BikePart objects
	Public Overrides Function GetHashCode() As Integer
		Return Me.Id.GetHashCode()
	End Function

	' Override ToString to return a custom string representation of the object
	Public Overrides Function ToString() As String
		Return "BikePart ID: " & Me.Id
	End Function
End Class
$vbLabelText   $csharpLabel

在這段程式碼中,BikePart 是我們的公共類,它包含一個公共字串 ID 來識別每個自行車零件。 我們重寫了 ToString 方法,以便更好地列印自行車零件的 ID,並且為了進行比較,我們也重寫了 EqualsGetHashCode 方法。

使用謂語查找。

現在我們有了 BikePart 類,我們可以建立一個自行車零件列表,並使用Find根據零件 ID 定位特定零件。 讓我們考慮以下範例:

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    // Print the found BikePart's ID to the console
    Console.WriteLine(chainRingPart.ToString());
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    // Print the found BikePart's ID to the console
    Console.WriteLine(chainRingPart.ToString());
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"}
	}

	' Define a predicate to find a BikePart with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function
	Dim chainRingPart As BikePart = bikeParts.Find(findChainRingPredicate)

	' Print the found BikePart's ID to the console
	Console.WriteLine(chainRingPart.ToString())
End Sub
$vbLabelText   $csharpLabel

在這段程式碼中,我們實例化了四個具有唯一 ID 的 BikePart 物件。 接下來,我們建立一個謂詞 findChainRingPredicate,用於檢查自行車零件是否具有 ID"鏈輪 ID"。 最後,我們使用定義的謂詞對自行車零件清單呼叫 Find,並將找到的零件的 ID 列印到控制台。

瞭解謂語參數

您可能想知道我們 Find 方法中的Predicate match參數。 在這裡,您可以定義 Find 方法傳回元素的條件。 在我們的例子中,我們希望 Find 方法傳回與"鏈環 ID"相符的第一個元素。

如果沒有元素滿足謂詞中定義的條件,則 Find 方法將傳回預設值。 例如,如果您正在處理整數數組,並且您的謂詞找不到匹配項,則 Find 方法將傳回"0",這是 C# 中整數的預設值。

線性搜尋原理

需要注意的是,Find 函數會對整個陣列、列表或集合進行線性搜尋。 這表示它會從第一個元素開始,依序檢查接下來的每個元素,直到找到滿足謂語的元素首次出現為止。

在某些情況下,您可能想要找出滿足謂語的最後一個元素,而不是第一個元素。 為此,C# 提供了 FindLast 函數。

FindIndexFindLastIndex

正如 Find 可以幫助您找到與指定謂詞相符的元素的第一個實例一樣,C# 也提供了 FindIndexFindLastIndex 方法,分別給出與您的條件相符的第一個和最後一個元素的索引。

讓我們試舉一個例子:

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Find the index of the first and last occurrence of the specified BikePart
    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    // Print the indices to the console
    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find a BikePart with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Find the index of the first and last occurrence of the specified BikePart
    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    // Print the indices to the console
    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects with an additional duplicate entry
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"},
		New BikePart With {.Id = "Chain Ring ID"}
	}

	' Define a predicate to find a BikePart with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function

	' Find the index of the first and last occurrence of the specified BikePart
	Dim firstChainRingIndex As Integer = bikeParts.FindIndex(findChainRingPredicate)
	Dim lastChainRingIndex As Integer = bikeParts.FindLastIndex(findChainRingPredicate)

	' Print the indices to the console
	Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}")
	Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}")
End Sub
$vbLabelText   $csharpLabel

FindAll 的力量

FindAll 方法顧名思義,檢索集合中所有滿足謂詞的元素。 當您需要根據特定條件篩選元素時,就會用到它。 FindAll 方法傳回包含所有符合元素的新清單。

以下是一個程式碼範例:

using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find all BikeParts with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Use FindAll to get all matching BikePart objects
    List<BikePart> chainRings = bikeParts.FindAll(findChainRingPredicate);

    // Print the count and details of each found BikePart
    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}
using System;
using System.Collections.Generic;

public static void Main()
{
    // Create a list of BikePart objects with an additional duplicate entry
    List<BikePart> bikeParts = new List<BikePart>
    {
        new BikePart { Id = "Chain Ring ID" },
        new BikePart { Id = "Crank Arm ID" },
        new BikePart { Id = "Regular Seat ID" },
        new BikePart { Id = "Banana Seat ID" },
        new BikePart { Id = "Chain Ring ID" }, // Added a second chain ring
    };

    // Define a predicate to find all BikeParts with a specific ID
    Predicate<BikePart> findChainRingPredicate = (BikePart bp) => { return bp.Id == "Chain Ring ID"; };

    // Use FindAll to get all matching BikePart objects
    List<BikePart> chainRings = bikeParts.FindAll(findChainRingPredicate);

    // Print the count and details of each found BikePart
    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}
Imports System
Imports System.Collections.Generic

Public Shared Sub Main()
	' Create a list of BikePart objects with an additional duplicate entry
	Dim bikeParts As New List(Of BikePart) From {
		New BikePart With {.Id = "Chain Ring ID"},
		New BikePart With {.Id = "Crank Arm ID"},
		New BikePart With {.Id = "Regular Seat ID"},
		New BikePart With {.Id = "Banana Seat ID"},
		New BikePart With {.Id = "Chain Ring ID"}
	}

	' Define a predicate to find all BikeParts with a specific ID
	Dim findChainRingPredicate As Predicate(Of BikePart) = Function(bp As BikePart)
		Return bp.Id = "Chain Ring ID"
	End Function

	' Use FindAll to get all matching BikePart objects
	Dim chainRings As List(Of BikePart) = bikeParts.FindAll(findChainRingPredicate)

	' Print the count and details of each found BikePart
	Console.WriteLine($"Found {chainRings.Count} Chain Rings:")
	For Each chainRing As BikePart In chainRings
		Console.WriteLine(chainRing.ToString())
	Next chainRing
End Sub
$vbLabelText   $csharpLabel

將 IronPDF 融入畫面。

我們的 C# Find 知識可以利用的一個關鍵領域是使用 IronPDF 進行 PDF 內容處理,IronPDF 是用於 PDF 處理的強大 C# 函式庫。

假設我們正在處理一份 PDF 文件,其中包含各種自行車零件的資訊。 通常,我們需要在這些內容中找出特定的部分。 這就是 IronPDF 與 C# Find 方法結合提供強大解決方案的地方。

首先,我們將使用IronPDF從 PDF 中提取文本,然後我們可以使用之前學過的 FindFindAll 方法來定位提取文本中的特定部分。

using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // Load and extract text from a PDF document
        PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
        string pdfText = pdf.ExtractAllText();

        // Split the extracted text into lines
        List<string> pdfLines = pdfText.Split('\n').ToList();

        // Define a predicate to find lines that contain a specific text
        Predicate<string> findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };

        // Use FindAll to get all lines containing the specified text
        List<string> chainRingLines = pdfLines.FindAll(findChainRingPredicate);

        // Print the count and content of each found line
        Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
        foreach (string line in chainRingLines)
        {
            Console.WriteLine(line);
        }
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // Load and extract text from a PDF document
        PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
        string pdfText = pdf.ExtractAllText();

        // Split the extracted text into lines
        List<string> pdfLines = pdfText.Split('\n').ToList();

        // Define a predicate to find lines that contain a specific text
        Predicate<string> findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };

        // Use FindAll to get all lines containing the specified text
        List<string> chainRingLines = pdfLines.FindAll(findChainRingPredicate);

        // Print the count and content of each found line
        Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
        foreach (string line in chainRingLines)
        {
            Console.WriteLine(line);
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class Program
	Public Shared Sub Main()
		' Load and extract text from a PDF document
		Dim pdf As PdfDocument = PdfDocument.FromFile("C:\Users\Administrator\Desktop\bike.pdf")
		Dim pdfText As String = pdf.ExtractAllText()

		' Split the extracted text into lines
		Dim pdfLines As List(Of String) = pdfText.Split(ControlChars.Lf).ToList()

		' Define a predicate to find lines that contain a specific text
		Dim findChainRingPredicate As Predicate(Of String) = Function(line As String)
			Return line.Contains("Chain Ring ID")
		End Function

		' Use FindAll to get all lines containing the specified text
		Dim chainRingLines As List(Of String) = pdfLines.FindAll(findChainRingPredicate)

		' Print the count and content of each found line
		Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':")
		For Each line As String In chainRingLines
			Console.WriteLine(line)
		Next line
	End Sub
End Class
$vbLabelText   $csharpLabel

在這段程式碼中,我們加載了一個 PDF 文件,提取了其中的文本,將其拆分成行,然後使用 FindAll 來查找所有提及"鏈環 ID"的行。

 如何在 VB.NET 中檢視 PDF 檔案:圖 1

這是一個如何在實際場景中將 Find 方法與 IronPDF 結合使用的基本範例。 它展示了 C# 的實用性和多功能性,以及其強大的函式庫,這些函式庫可讓您的程式設計工作更輕鬆、更有效率。

結論

在本教程中,我們深入研究了 C# 的 Find 方法及其相關方法,FindIndexFindLastIndexFindAll。 我們探討了這些工具的用途,探索了一些程式碼範例,並發掘了在哪些情況下它們最有效。

我們也使用 IronPDF 函式庫涉足 PDF 操作的世界。 同樣,我們也看到了我們 Find 方法知識在提取和搜尋 PDF 文件內容方面的實際應用。

IronPDF 提供免費的 IronPDF試用版,提供絕佳的機會讓您探索其功能,並判斷它如何能讓您的 C# 專案獲益。 如果您決定在試用期結束後繼續使用 IronPDF,許可證從 $999 開始。

常見問題解答

C# Find 函數對於開發人員來說是如何工作的?

C# Find 函數允許開發人員在集合、陣列或列表中找到符合謂詞所定義的特定條件的第一個元素。此功能有助於簡化編碼過程。

什麼是謂詞,C# 中如何使用?

C# 中的謂詞是一個代表具有特定條件的方法的委託。它用於像 Find 這樣的方法中,用於測試集合中的每個元素,返回滿足條件的那些元素。

我可以在 C# 中與自定義類一起使用 Find 方法嗎?

是的,您可以通過定義一個與類的元素的搜索標準匹配的謂詞來與自定義類一起使用 Find 方法,例如查找具有特定屬性值的對象。

如果 Find 方法中沒有元素符合標準會發生什麼情況?

如果在 Find 方法中沒有元素符合謂詞指定的標準,它將返回一個預設值,例如參考類型返回 null 或值類型返回 0

C# 中的 Find 和 FindAll 有什麼區別?

Find 方法返回匹配謂詞的第一個元素,而 FindAll 返回滿足謂詞條件的所有元素的列表。

FindIndex 和 FindLastIndex 方法有何不同?

FindIndex 返回匹配謂詞的第一個元素的索引,而 FindLastIndex 返回匹配條件的最後一個元素的索引。

如何將 PDF 庫與 C# Find 集成以進行文本搜索?

通過使用 PDF 庫,您可以從 PDF 中提取文本並利用 Find 方法來搜索文本中特定的內容,這使文檔處理更加有效。

是否可以使用 Find 方法根據屬性搜索元素?

是的,您可以基於元素屬性定義一個謂詞以搜索特定標準,例如查找具有特定 ID 或屬性的對象。

Find 方法在大型數據集合中效率如何?

Find 方法執行線性搜索,按順序檢查每個元素。雖然簡單,但由於其 O(n) 複雜性,對於非常大的集合可能不是最有效的。

PDF 庫對 C# 開發人員有什麼好處?

PDF 庫提供強大的 PDF 處理能力,使開發人員能夠輕鬆地使用 C# 提取、操作和搜索 PDF 內容,從而提升文檔相關任務的效率。

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 小時在線上。
聊天
電子郵件
打電話給我