開發者更新

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

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2025年7月28日

歡迎來到我們的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;
    }
}

在此程式碼中,BikePart是我們的公共類別,它包含一個公共字串ID以識別每個單車部件。 我們重寫了GetHashCode方法以用於比較目的。

使用謂詞應用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());
}

在此程式碼中,我們建立了四個具有唯一ID的BikePart物件。 接下來,我們建立了檢查單車部件是否具有"鏈輪ID"的謂詞findChainRingPredicate。 最後,我們使用我們定義的謂詞在我們的單車部件列表上調用Find並將找到的部件ID列印到控制台。

了解謂詞參數

您可能對我們Find方法中的謂詞匹配參數感到好奇。 這是您定義Find方法返回一個元素的條件的地方。 在我們的情況下,我們希望Find方法返回與"鏈輪ID"匹配的第一個元素。

如果沒有元素滿足您謂詞中定義的條件,Find方法將返回一個預設值。 例如,如果您正在使用整數陣列,而您的謂詞未找到匹配項,Find方法將返回'0',這是C#中整數的預設值。

線性搜索原則

需要注意的是,Find函式在整個陣列、列表或集合中進行線性搜索。 這意味著它從第一個元素開始,按順序檢查每個後續元素,直到定位到滿足謂詞的第一個元素出現。

在某些情況下,您可能希望定位滿足謂詞的最後一個元素,而不是第一個。 為此,C#提供了FindLast函式。

FindLastIndex

就像FindLastIndex方法,分別為您提供匹配條件的第一個和最後一個元素的索引。

讓我們嘗試一個例子:

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}");
}

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());
    }
}

將IronPDF引入畫面

我們的C#查找知識可用於PDF內容操作的一個重要領域是使用IronPDF,一個用於PDF處理的強大C#程式庫。

假設我們正在處理包含各種單車部件資訊的PDF文件。 通常,我們需要在此內容中定位特定部件。 這就是IronPDF和C#查找方法相結合提供強大解決方案的地方。

首先,我們會使用IronPDF來從PDF中提取文字,然後可以使用我們之前學到的FindAll方法定位提取文字中的特定部分。

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);
        }
    }
}

在此程式碼中,我們載入了一個PDF,提取了文字,將其分割成行,然後使用FindAll來定位所有提到'鏈輪ID'的行。

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

這是一個關於如何在實際場景中與IronPDF一起使用Find方法的基本例子。 它演示了C#與強大的程式庫一起使用的實用性和多樣性,這有助於使您的程式設計任務更加簡單和高效。

結論

在本教程中,我們深入探討了C# Find方法及其相關 lang="en">的FindAll。 我們探討了它們的用途,探索了一些程式碼範例,並揭示了它們最有效的使用情境。

我們還探索了使用IronPDF程式庫進行PDF操作的世界。 同樣地,我們看到了在PDF文件內提取和搜索內容的實際應用中使用Find方法知識的實際應用。

IronPDF提供了免費試用IronPDF的機會,使您可以探索其功能並確定它如何能為您的C#專案帶來益處。 如果您決定在試用後繼續使用IronPDF, 授權起價為$999。

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

閱讀更多

相關文章