
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 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在此代码中,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());
}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在此代码中,我们实例化了四个具有唯一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}");
}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 SubFindAll的力量
顾名思义,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());
}
}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引入 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);
}
}
}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) line.Contains("Chain Ring ID")
' 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
End Sub
End Class在此代码中,我们加载了一个PDF,提取了文本,将其拆分为行,然后使用FindAll定位提到'Chain Ring ID'的所有行。

这是一个关于如何在实际场景中将Find方法与IronPDF一起使用的基本示例。 它展示了 C# 的实用性和多功能性以及其强大的库,有助于让您的编程任务更轻松、更高效。
结论
在本教程中,我们深入研究了C#的FindAll。 我们探索了它们的用法,研究了一些代码示例,并介绍了它们最有效的情况。
我们还进入了使用 IronPDF 库进行 PDF 操作的世界。 同样,我们看到我们的Find方法知识在提取和搜索PDF文档内容方面的实际应用。
IronPDF 提供免费的 试用版 IronPDF,提供了绝佳的机会来探索其功能并确定它如何能够为您的 C# 项目带来好处。 如果您决定在试用后继续使用IronPDF,许可证价格开始于$999。

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


