跳過到頁腳內容
.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;
    }
}
$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());
}
$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}");
}
$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());
    }
}
$vbLabelText   $csharpLabel

將IronPDF引入整個過程中

我們的 C# Find 知識可以應用於使用IronPDF(一個功能強大的 C# PDF 處理庫)進行 PDF 內容操作的關鍵領域。

假設我們正在處理一份包含各種自行車零件資訊的 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);
        }
    }
}
$vbLabelText   $csharpLabel

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

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

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

結論

在本教程中,我們深入研究了 C# 的 Find 方法及其相關方法 FindLastIndexFindAll。 我們探索了它們的用途,研究了一些程式碼範例,並發現了它們最有效的應用場景。

我們也嘗試使用IronPDF庫進行 PDF 處理。 同樣,我們也看到了我們 Find 方法知識在提取和搜尋 PDF 文件內容方面的實際應用。

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

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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me