跳過到頁腳內容
.NET幫助

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

歡迎來到我們關於 C# 有用的 Find 函數的教程。 你剛剛發現了一個強大的功能,可以簡化你的編碼過程。 因此,無論你是經驗豐富的編程人員還是剛起步,本教程將引導你完成所有元素以幫助你入門。

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 方法以便用於比較目的。

使用條件運算符的 Find

現在有了 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 "Chain Ring ID"。 最後,我們使用定義的條件運算符對自行車零件列表調用 Find,並將找到的部件的 ID 打印到控制台。

理解條件運算符參數

你可能會對我們 Find 方法中的 條件運算符 匹配 參數感到好奇。 這是你定義 Find 方法返回元素的條件的地方。 在我們的案例中,我們希望 Find 方法返回匹配 "Chain Ring 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 內容操作,這是一個用於 PDF 處理的強大 C# 庫。

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

First, we'd use IronPDF to extract the text from our PDF and then we can use the Find or FindAll method that we've learned about earlier to locate the specific part in the extracted text.

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 找到所有提到 'Chain Ring ID' 的行。

如何在 VB.NET 中查看 PDF 文件:圖 1

這是一個如何在實際場景中使用 Find 方法與 IronPDF 結合的基本示例。 它展示了 C# 的實用性和多功能性及其強大的庫,這些庫幫助你更輕鬆、更高效地完成編程任務。

結論

在本教程中,我們深入探討了 C# 的 Find 方法及其相關的 FindIndexFindLastIndexFindAll。 我們探索了它們的用途,查看了一些代碼示例,並揭示了其最有效的情況。

我們還涉足了使用 IronPDF 庫的 PDF 操作世界。 同樣,我們看到了我們的 Find 方法知識在從 PDF 文檔中提取和搜索內容的實際應用。

IronPDF 提供了一個免費的試用版,提供了一個探索其功能並確定其對 C# 項目有何好處的絕佳機會。 如果你決定在試用後繼續使用 IronPDF,許可證從 $799 開始。

常見問題解答

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 內容,從而提升文檔相關任務的效率。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。