跳至页脚内容
.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;
    }
}
$vbLabelText   $csharpLabel

在这段代码中,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());
}
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 "Chain Ring ID"。 最后,我们在自行车零件列表上调用Find,使用我们定义的谓词,并将找到的零件ID打印到控制台。

理解谓词参数

您可能会对我们Find方法中的谓词匹配参数感到好奇。 这就是您定义Find方法返回元素的条件的地方。 在我们的例子中,我们希望Find方法返回第一个与"Chain Ring 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}");
}
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 进行 PDF 内容操作,IronPDF 是处理 PDF 的强大 C# 库。

假设我们正在处理一个包含各种自行车零件信息的 PDF 文档。 通常,我们需要在这些内容中定位特定部件。 这就是 IronPDF 和 C# Find 方法结合提供强大解决方案的地方。

首先,我们将使用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);
        }
    }
}
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定位提到"Chain Ring ID"的所有行。

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

这是一个基本示例,说明了Find方法如何与IronPDF一起用于实际场景中。 它展示了 C# 的实用性和多功能性以及其强大的库,有助于让您的编程任务更轻松、更高效。

结论

在本教程中,我们深入探讨了C#的FindAll。 我们探索了它们的用法,研究了一些代码示例,并介绍了它们最有效的情况。

我们还进入了使用 IronPDF 库进行 PDF 操作的世界。 同样,我们看到我们对Find方法知识的实际应用,如在PDF文档中提取和搜索内容。

IronPDF 提供免费的 试用版 IronPDF,提供了绝佳的机会来探索其功能并确定它如何能够为您的 C# 项目带来好处。 如果您决定在试用期后继续使用IronPDF,许可证从$799开始。

常见问题解答

C# 查找函数对开发人员如何工作?

C# 查找函数允许开发人员找到集合、数组或列表中第一个满足特定条件的元素。此功能对简化编码过程很有用。

什么是谓词,在 C# 中如何使用?

在 C# 中,谓词是一个表示具有特定条件的方法的委托。它用于诸如 Find 等方法来测试集合中的每个元素,返回满足条件的元素。

我可以在 C# 中将查找方法与自定义类一起使用吗?

是的,您可以通过定义一个匹配自定义类元素搜索条件的谓词来使用查找方法,例如找到具有特定属性值的对象。

如果在查找方法中没有元素匹配条件,会发生什么?

如果在 Find 方法中没有元素符合谓词指定的条件,则返回默认值,例如引用类型的 null 或值类型的 0

Find 和 FindAll 在 C# 中有什么区别?

Find 方法返回第一个符合谓词的元素,而 FindAll 返回所有满足谓词条件的元素列表。

FindIndex 和 FindLastIndex 方法有何不同?

FindIndex 返回第一个符合谓词元素的索引,而 FindLastIndex 返回最后一个符合条件元素的索引。

如何将 PDF 库与 C# Find 集成进行文本搜索?

通过使用 PDF 库,您可以从 PDF 中提取文本并利用查找方法在文本中搜索特定内容,从而提高文档处理的效率。

是否可以使用 Find 根据元素的属性进行搜索?

是的,您可以根据元素属性定义谓词来搜索特定条件,例如找到具有特定 ID 或属性的对象。

Find 方法对于大型数据集合有多高效?

Find 方法执行线性搜索,按顺序检查每个元素。虽然简单,但它可能不是非常大型集合中最有效的,因为它的复杂度是 O(n)。

对于 C# 开发人员来说,PDF 库有什么好处?

PDF 库提供了强大的 PDF 处理能力,允许开发人员轻松提取、操作和搜索 PDF 内容,利用 C# 提高文档相关任务的效率。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

Iron Support Team

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