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
在这段代码中,BikePart 是我们的公共类,它包含一个公共字符串 ID 来标识每个自行车部件。 我们重写了 ToString 方法,以便更好地打印自行车零件的 ID,并且为了进行比较,我们也重写了 Equals 和 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());
}
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"链轮 ID"。 最后,我们使用定义的谓词对自行车零件列表调用 Find,并将找到的零件 ID 打印到控制台。
理解谓词参数
您可能想知道我们 Find 方法中的Predicate match参数。 在这里,您可以定义 Find 方法返回元素的条件。 在我们的例子中,我们希望 Find 方法返回与"链环 ID"匹配的第一个元素。
如果没有元素满足谓词中定义的条件,则 Find 方法将返回默认值。 例如,如果您正在处理整数数组,并且您的谓词找不到匹配项,则 Find 方法将返回"0",这是 C# 中整数的默认值。
线性搜索原则
需要注意的是,Find 函数会对整个数组、列表或集合进行线性搜索。 这意味着它从第一个元素开始,并按顺序检查每一个后续元素,直到找到满足谓词的第一个元素为止。
在某些情况下,您可能想找到满足谓词的最后一个元素而不是第一个。 为此,C# 提供了 FindLast 函数。
FindIndex 和 FindLastIndex
正如 Find 可以帮助您找到与指定谓词匹配的元素的第一个实例一样,C# 还提供了 FindIndex 和 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}");
}
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
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
引入 IronPDF
我们 C# Find 知识可以应用的一个重要领域是使用 IronPDF 进行 PDF 内容操作,IronPDF 是处理 PDF 的强大 C# 库。
假设我们正在处理一个包含各种自行车零件信息的 PDF 文档。 通常,我们需要在这些内容中定位特定部件。 这就是 IronPDF 和 C# Find 方法结合提供强大解决方案的地方。
首先,我们将使用IronPDF从 PDF 中提取文本,然后我们可以使用之前学过的 Find 或 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);
}
}
}
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
在这段代码中,我们加载了一个 PDF 文件,提取了其中的文本,将其拆分成行,然后使用 FindAll 来查找所有提及"链环 ID"的行。

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




