.NET 帮助

C# 查找(开发人员如何使用)

发布 2023年六月13日
分享:

欢迎来到我们的 C# 便捷 Find 函数教程。您刚刚发现了一个可以简化编码过程的强大功能。因此,无论您是经验丰富的编码员还是刚刚入门,本教程都将指导您了解所有元素,让您轻松上手。

查找的基础知识

Find "的核心功能是查找集合、数组或列表中满足指定谓词的第一个元素。你会问什么是谓词?在编程中,谓词是一个函数,用于测试为集合中的元素定义的某些条件。

现在,让我们深入了解一个公共类示例。


public class BikePart
{
    public string id { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null 
 !(obj is BikePart))
            return false;

        return this.id == ((BikePart)obj).id;
    }

    public override int GetHashCode()
    {
        return this.id.GetHashCode();
    }

    public override string ToString()
    {
        return "BikePart ID: " + this.id;
    }
}

public class BikePart
{
    public string id { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null 
 !(obj is BikePart))
            return false;

        return this.id == ((BikePart)obj).id;
    }

    public override int GetHashCode()
    {
        return this.id.GetHashCode();
    }

    public override string ToString()
    {
        return "BikePart ID: " + this.id;
    }
}
Public Class BikePart
	Public Property id() As String

	Public Overrides Function Equals(ByVal obj As Object) As Boolean
		If obj Is Nothing (Not (TypeOf obj Is BikePart)) Then
			Return False
		End If

		Return Me.id = DirectCast(obj, BikePart).id
	End Function

	Public Overrides Function GetHashCode() As Integer
		Return Me.id.GetHashCode()
	End Function

	Public Overrides Function ToString() As String
		Return "BikePart ID: " & Me.id
	End Function
End Class
VB   C#

在这段代码中,"BikePart "是我们的公共类,它包含一个公共字符串 ID,用于标识每个自行车零件。我们重载了 ToString 方法,以便很好地打印自行车零件的 ID,我们还重载了 EqualsGetHashCode 方法,以便进行比较。

使用谓词查找

现在我们有了 "BikePart "类,可以创建一个自行车零件列表,并使用 查找 来根据 ID 查找特定部件。请看下面的例子:


public static void Main()
{
    List bikeParts = new List
    {
        new BikePart { id = "Chain Ring ID" },
        new BikePart { id = "Crank Arm ID" },
        new BikePart { id = "Regular Seat ID" },
        new BikePart { id = "Banana Seat ID" },
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    Console.WriteLine(chainRingPart.ToString());
}

public static void Main()
{
    List bikeParts = new List
    {
        new BikePart { id = "Chain Ring ID" },
        new BikePart { id = "Crank Arm ID" },
        new BikePart { id = "Regular Seat ID" },
        new BikePart { id = "Banana Seat ID" },
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };
    BikePart chainRingPart = bikeParts.Find(findChainRingPredicate);

    Console.WriteLine(chainRingPart.ToString());
}
Public Shared Sub Main()
	Dim bikeParts As New List 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"}
	}

	Dim findChainRingPredicate As Predicate = Function(bp As BikePart)
		Return bp.id = "Chain Ring ID"
	End Function
	Dim chainRingPart As BikePart = bikeParts.Find(findChainRingPredicate)

	Console.WriteLine(chainRingPart.ToString())
End Sub
VB   C#

在这段代码中,我们实例化了四个具有唯一 ID 的 BikePart 对象。接着,我们创建一个谓词 findChainRingPredicate 来检查自行车零件是否具有 ID "链环 ID"。最后,我们使用定义的谓词在自行车零件列表中调用 Find 并将找到的零件 ID 打印到控制台。

了解谓词参数

您可能想知道 Find 方法中的 Predicate match 参数。您可以在这里定义 Find 方法返回元素的条件。在我们的例子中,我们希望 Find 方法返回与 "链环 ID "匹配的第一个元素。

如果没有元素满足谓词中定义的条件,Find 方法将返回一个默认值。例如,如果您正在处理一个整数数组,而您的谓词没有找到匹配的元素,那么 Find 方法将返回 "0",即 C# 中整数的默认值。

线性搜索原理

必须注意的是,Find函数在整个数组、列表或集合中进行线性搜索。这意味着它会从第一个元素开始,依次检查后面的每个元素,直到找到第一个满足谓词的元素。

在某些情况下,您可能希望找到满足谓词的最后一个元素,而不是第一个元素。为此,C# 提供了 FindLast 函数。

FindIndexFindLastIndex

正如 Find 可以帮助您找到符合指定谓词的元素的首次出现,C# 也提供了 FindIndexFindLastIndex 方法,分别为您提供符合条件的第一个和最后一个元素的索引。

让我们举例说明:


public static void Main()
{
    List bikeParts = new List
    {
        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
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };

    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}

public static void Main()
{
    List bikeParts = new List
    {
        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
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };

    int firstChainRingIndex = bikeParts.FindIndex(findChainRingPredicate);
    int lastChainRingIndex = bikeParts.FindLastIndex(findChainRingPredicate);

    Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}");
    Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}");
}
Public Shared Sub Main()
	Dim bikeParts As New List 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"}
	}

	Dim findChainRingPredicate As Predicate = Function(bp As BikePart)
		Return bp.id = "Chain Ring ID"
	End Function

	Dim firstChainRingIndex As Integer = bikeParts.FindIndex(findChainRingPredicate)
	Dim lastChainRingIndex As Integer = bikeParts.FindLastIndex(findChainRingPredicate)

	Console.WriteLine($"First Chain Ring ID found at index: {firstChainRingIndex}")
	Console.WriteLine($"Last Chain Ring ID found at index: {lastChainRingIndex}")
End Sub
VB   C#

FindAll 的力量

顾名思义,FindAll方法会检索集合中所有满足谓词条件的元素。当您需要根据某些条件过滤元素时,就会用到该方法。FindAll` 方法会返回一个包含所有匹配元素的新 List。

下面是一个代码示例:


public static void Main()
{
    List bikeParts = new List
    {
        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
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };

    List chainRings = bikeParts.FindAll(findChainRingPredicate);

    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}

public static void Main()
{
    List bikeParts = new List
    {
        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
    };

    Predicate findChainRingPredicate = (BikePart bp) => { return bp.id == "Chain Ring ID"; };

    List chainRings = bikeParts.FindAll(findChainRingPredicate);

    Console.WriteLine($"Found {chainRings.Count} Chain Rings:");
    foreach (BikePart chainRing in chainRings)
    {
        Console.WriteLine(chainRing.ToString());
    }
}
Public Shared Sub Main()
	Dim bikeParts As New List 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"}
	}

	Dim findChainRingPredicate As Predicate = Function(bp As BikePart)
		Return bp.id = "Chain Ring ID"
	End Function

	Dim chainRings As List = bikeParts.FindAll(findChainRingPredicate)

	Console.WriteLine($"Found {chainRings.Count} Chain Rings:")
	For Each chainRing As BikePart In chainRings
		Console.WriteLine(chainRing.ToString())
	Next chainRing
End Sub
VB   C#

将 IronPDF 纳入其中

使用功能强大的 C&num IronPDF 对 PDF 内容进行操作是我们可以利用 C# Find 知识的一个重要领域;

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

首先,我们使用 IronPDF从我们的 PDF 中提取文本然后,我们可以使用前面学到的 FindFindAll 方法在提取的文本中找到特定部分。


using IronPdf;

PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
string pdfText = pdf.ExtractAllText();

// Assuming our PDF text is split into lines
List pdfLines = pdfText.Split('\n').ToList();

Predicate findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };
List chainRingLines = pdfLines.FindAll(findChainRingPredicate);

Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
foreach (string line in chainRingLines)
{
    Console.WriteLine(line);
}

using IronPdf;

PdfDocument pdf = PdfDocument.FromFile(@"C:\Users\Administrator\Desktop\bike.pdf");
string pdfText = pdf.ExtractAllText();

// Assuming our PDF text is split into lines
List pdfLines = pdfText.Split('\n').ToList();

Predicate findChainRingPredicate = (string line) => { return line.Contains("Chain Ring ID"); };
List chainRingLines = pdfLines.FindAll(findChainRingPredicate);

Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':");
foreach (string line in chainRingLines)
{
    Console.WriteLine(line);
}
Imports Microsoft.VisualBasic
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("C:\Users\Administrator\Desktop\bike.pdf")
Private pdfText As String = pdf.ExtractAllText()

' Assuming our PDF text is split into lines
Private pdfLines As List = pdfText.Split(ControlChars.Lf).ToList()

Private findChainRingPredicate As Predicate = Function(line As String)
	Return line.Contains("Chain Ring ID")
End Function
Private chainRingLines As List = pdfLines.FindAll(findChainRingPredicate)

Console.WriteLine($"Found {chainRingLines.Count} lines mentioning 'Chain Ring ID':")
For Each line As String In chainRingLines
	Console.WriteLine(line)
Next line
VB   C#

在这段代码中,我们加载了 PDF,提取了文本,将其分成几行,然后使用 FindAll 查找所有提到 "Chain Ring ID "的行。

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

这是一个基本示例,说明如何在实际场景中将 Find 方法与 IronPDF 结合使用。它展示了 C# 及其强大库的实用性和多功能性,可帮助您更轻松、更高效地完成编程任务。

结论

在本教程中,我们深入研究了 C# Find** 方法及其近似方法 FindIndexFindLastIndexFindAll。我们探讨了它们的用途,浏览了一些代码示例,并揭示了它们在哪些情况下最有效。

我们还使用 IronPDF 库涉足了 PDF 操作领域。同样,我们还看到了 "Find "方法知识在提取和搜索 PDF 文档内容中的实际应用。

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

< 前一页
C# 类型(如何为开发人员工作)
下一步 >
C# 新手指南(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,746,704 查看许可证 >