Zum Fußzeileninhalt springen
.NET HILFE

C# Finden (Wie es für Entwickler funktioniert)

Welcome to our tutorial on C#'s handy Find function. You've just stumbled upon a powerful feature that can streamline your coding process. So, whether you're a seasoned coder or just starting out, this tutorial will walk you through all the elements to get you going.

The Basics of Find

At its core, Find is a function that allows you to locate the first element in a collection, array, or list that satisfies a specified predicate. What's a predicate, you ask? In programming, a predicate is a function that tests certain conditions defined for elements in a collection.

Now, let's dive into a public class example.

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
$vbLabelText   $csharpLabel

In this code, BikePart is our public class, and it contains a public string ID to identify each bike part. We have overridden the ToString method to print the ID of the bike part nicely, and we have also overridden the Equals and GetHashCode methods for comparison purposes.

Employing Find with Predicates

Now that we have our BikePart class, we can create a list of bike parts and use Find to locate specific parts based on their IDs. Let's consider the following example:

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
$vbLabelText   $csharpLabel

In this code, we instantiate four BikePart objects with unique IDs. Next, we create a predicate findChainRingPredicate that checks if a bike part has the ID "Chain Ring ID". Finally, we call Find on our list of bike parts using the predicate we defined and print the found part's ID to the console.

Understanding the Predicate Parameter

You might be wondering about the Predicate match parameter in our Find method. This is where you define the conditions under which the Find method returns an element. In our case, we wanted the Find method to return the first element that matches the "Chain Ring ID".

If no element satisfies the conditions defined in your predicate, the Find method will return a default value. For instance, if you're working with an array of integers and your predicate doesn't find a match, the Find method will return '0', the default value for integers in C#.

The Linear Search Principle

It's essential to note that the Find function conducts a linear search across the entire array, list, or collection. This means it starts at the first element and inspects each following element in sequence until it locates the first occurrence of an element satisfying the predicate.

In some cases, you might want to locate the last element that satisfies the predicate instead of the first one. For this purpose, C# provides the FindLast function.

FindIndex and FindLastIndex

Just as Find helps you locate the first occurrence of an element that matches your specified predicate, C# also provides FindIndex and FindLastIndex methods to give you the indices of the first and last elements that match your conditions, respectively.

Let's try an example:

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
$vbLabelText   $csharpLabel

The Power of FindAll

The FindAll method, as the name suggests, retrieves all elements in the collection that satisfy the predicate. It is used when you need to filter elements based on certain conditions. The FindAll method returns a new List with all the matched elements.

Here's a code example:

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
$vbLabelText   $csharpLabel

Bringing IronPDF into the Picture

A crucial area where our C# Find knowledge can be utilized is PDF content manipulation using IronPDF, a powerful C# library for PDF processing.

Suppose we're working with a PDF document containing information on various bike parts. Often, we need to locate specific parts within this content. This is where IronPDF and the C# Find method combine to provide a powerful solution.

First, we'd use IronPDF to extract the text from our PDF and then we can use the Find or FindAll method that we've learned about earlier to locate the specific part in the extracted text.

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
$vbLabelText   $csharpLabel

In this code, we've loaded a PDF, extracted the text, split it into lines, and then used FindAll to locate all lines mentioning 'Chain Ring ID'.

How to View PDF Files in VB.NET: Figure 1

This is a basic example of how the Find method can be used along with IronPDF in a practical scenario. It demonstrates the utility and versatility of C# along with its powerful libraries that help make your programming tasks easier and more efficient.

Conclusion

In this tutorial, we dove deep into the C# Find method and its relatives, FindIndex, FindLastIndex, and FindAll. We explored their uses, explored some code examples, and uncovered the circumstances where they are most effective.

We also ventured into the world of PDF manipulation using the IronPDF library. Likewise, we saw a practical application of our Find method knowledge in extracting and searching content within a PDF document.

IronPDF offers a free trial of IronPDF, providing an excellent opportunity to explore its functionalities and determine how it can benefit your C# projects. If you decide to continue using IronPDF after the trial, licenses start from $799.

Häufig gestellte Fragen

Wie funktioniert die C# Find-Funktion für Entwickler?

Die C# Find-Funktion ermöglicht es Entwicklern, das erste Element in einer Sammlung, einem Array oder einer Liste zu lokalisieren, das bestimmte Bedingungen erfüllt, die von einem Prädikat definiert werden. Diese Funktion ist nützlich, um den Kodierungsprozess zu optimieren.

Was ist ein Prädikat, und wie wird es in C# verwendet?

Ein Prädikat in C# ist ein Delegat, der eine Methode mit einer bestimmten Bedingung repräsentiert. Es wird in Methoden wie Find verwendet, um jedes Element in einer Sammlung zu testen und diejenigen zurückzugeben, die die Kriterien erfüllen.

Kann ich die Find-Methode mit einer benutzerdefinierten Klasse nutzen?

Ja, Sie können die Find-Methode mit einer benutzerdefinierten Klasse verwenden, indem Sie ein Prädikat definieren, das den Suchkriterien für die Elemente der Klasse entspricht, wie z.B. das Finden eines Objekts mit einem bestimmten Eigenschaftswert.

Was passiert, wenn keine Elemente in der Find-Methode den Kriterien entsprechen?

Wenn keine Elemente den vom Prädikat in der Find-Methode angegebenen Kriterien entsprechen, wird ein Standardwert zurückgegeben, z.B. null für Referenztypen oder 0 für Werttypen.

Was sind die Unterschiede zwischen Find und FindAll in C#?

Die Find-Methode gibt das erste Element zurück, das dem Prädikat entspricht, während FindAll eine Liste aller Elemente zurückgibt, die die Prädikatbedingungen erfüllen.

Wie unterscheiden sich die Methoden FindIndex und FindLastIndex?

FindIndex gibt den Index des ersten Elements zurück, das dem Prädikat entspricht, während FindLastIndex den Index des letzten Elements zurückgibt, das die Kriterien erfüllt.

Wie kann ich eine PDF-Bibliothek mit C# Find für die Textsuche integrieren?

Indem Sie eine PDF-Bibliothek verwenden, können Sie Text aus PDFs extrahieren und die Find-Methode nutzen, um nach spezifischem Inhalt innerhalb des Textes zu suchen, was sie für die Dokumentenverarbeitung effektiv macht.

Ist es möglich, nach Elementen anhand ihrer Eigenschaften mit Find zu suchen?

Ja, Sie können ein Prädikat basierend auf den Eigenschaften eines Elements definieren, um nach spezifischen Kriterien zu suchen, wie z.B. das Auffinden eines Objekts mit einer bestimmten ID oder einem bestimmten Attribut.

Wie effizient ist die Find-Methode für große Datensammlungen?

Die Find-Methode führt eine lineare Suche durch, bei der jedes Element der Reihe nach überprüft wird. Obwohl einfach, ist sie möglicherweise nicht die effizienteste Methode für sehr große Sammlungen aufgrund ihrer O(n)-Komplexität.

Welche Vorteile bietet eine PDF-Bibliothek für C#-Entwickler?

Eine PDF-Bibliothek bietet robuste PDF-Verarbeitungsfunktionen, die es Entwicklern ermöglichen, PDF-Inhalte einfach zu extrahieren, zu manipulieren und zu durchsuchen, wodurch die Effizienz von dokumentbezogenen Aufgaben erhöht wird.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen