Passer au contenu du pied de page
.NET AIDE

Trouver en C# (Comment ça fonctionne pour les développeurs)

Bienvenue dans notre tutoriel sur la fonction pratique Find de C#. Vous venez de découvrir une fonctionnalité puissante qui peut simplifier votre processus de codage. Ainsi, que vous soyez un codeur expérimenté ou que vous débutiez, ce tutoriel vous guidera à travers tous les éléments pour bien démarrer.

Les bases de Find

Au cœur, Find est une fonction qui vous permet de localiser le premier élément d'une collection, d'un tableau ou d'une liste qui satisfait un prédicat spécifié. Qu'est-ce qu'un prédicat, vous demandez-vous ? En programmation, un prédicat est une fonction qui teste certaines conditions définies pour les éléments dans une collection.

Passons maintenant à un exemple de classe publique.

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

Dans ce code, BikePart est notre classe publique et contient une chaîne publique ID pour identifier chaque pièce de vélo. Nous avons remplacé la méthode ToString pour imprimer joliment l'ID de la pièce de vélo, et nous avons également remplacé les méthodes Equals et GetHashCode à des fins de comparaison.

Utiliser Find avec des prédicats

Maintenant que nous avons notre classe BikePart, nous pouvons créer une liste de pièces de vélo et utiliser Find pour localiser des pièces spécifiques en fonction de leur ID. Considérons l'exemple suivant :

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

Dans ce code, nous instancions quatre objets BikePart avec des ID uniques. Ensuite, nous créons un prédicat findChainRingPredicate qui vérifie si une pièce de vélo a l'ID "Chain Ring ID". Enfin, nous utilisons Find sur notre liste de pièces de vélo en utilisant le prédicat que nous avons défini et nous imprimons l'ID de la pièce trouvée dans la console.

Comprendre le paramètre de prédicat

Vous vous demandez peut-être à propos du paramètre Predicate match dans notre méthode Find. C'est là que vous définissez les conditions sous lesquelles la méthode Find retourne un élément. Dans notre cas, nous voulions que la méthode Find retourne le premier élément qui correspond à "Chain Ring ID".

Si aucun élément ne satisfait aux conditions définies dans votre prédicat, la méthode Find renverra une valeur par défaut. Par exemple, si vous travaillez avec un tableau d'entiers et que votre prédicat ne trouve pas de correspondance, la méthode Find retournera '0', la valeur par défaut pour les entiers en C#.

Le principe de recherche linéaire

Il est essentiel de noter que la fonction Find effectue une recherche linéaire sur l'ensemble du tableau, de la liste ou de la collection. Cela signifie qu'elle commence par le premier élément et inspecte chaque élément suivant dans l'ordre jusqu'à ce qu'elle localise la première occurrence d'un élément satisfaisant le prédicat.

Dans certains cas, vous pourriez vouloir localiser le dernier élément qui satisfait le prédicat au lieu du premier. À cette fin, C# fournit la fonction FindLast.

FindIndex et FindLastIndex

Tout comme Find vous aide à localiser la première occurrence d'un élément qui correspond à votre prédicat spécifié, C# fournit également les méthodes FindIndex et FindLastIndex pour vous donner les indices des premiers et derniers éléments qui correspondent à vos conditions, respectivement.

Essayons un exemple :

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

La puissance de FindAll

La méthode FindAll, comme son nom l'indique, récupère tous les éléments de la collection qui satisfont le prédicat. Elle est utilisée lorsque vous avez besoin de filtrer des éléments en fonction de certaines conditions. La méthode FindAll retourne une nouvelle liste avec tous les éléments correspondants.

Voici un exemple de code :

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

Mettre IronPDF en scène

Un domaine crucial où notre connaissance de Find en C# peut être utilisée est la manipulation de contenu PDF avec IronPDF, une bibliothèque C# puissante pour le traitement des PDF.

Supposons que nous travaillions avec un document PDF contenant des informations sur différentes pièces de vélo. Souvent, nous devons localiser des pièces spécifiques dans ce contenu. C'est là que IronPDF et la méthode C# Find se combinent pour offrir une solution puissante.

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

Dans ce code, nous avons chargé un PDF, extrait le texte, divisé en lignes, puis utilisé FindAll pour localiser toutes les lignes mentionnant 'Chain Ring ID'.

Comment visualiser les fichiers PDF dans VB.NET : Figure 1

Ceci est un exemple de base de la manière dont la méthode Find peut être utilisée avec IronPDF dans un scénario concret. Il démontre l'utilité et la polyvalence de C# ainsi que ses bibliothèques puissantes qui facilitent et rendent vos tâches de programmation plus efficaces.

Conclusion

Dans ce tutoriel, nous avons plongé en profondeur dans la méthode Find de C# et ses variantes, FindIndex, FindLastIndex et FindAll. Nous avons exploré leurs utilisations, discuté de quelques exemples de code et mis en lumière les circonstances dans lesquelles elles sont les plus efficaces.

Nous avons également exploré le monde de la manipulation PDF en utilisant la bibliothèque IronPDF. De même, nous avons vu une application pratique de notre connaissance de la méthode Find dans l'extraction et la recherche de contenu au sein d'un document PDF.

IronPDF propose un essai gratuit d'IronPDF, offrant une excellente occasion d'explorer ses fonctionnalités et de déterminer comment elle peut profiter à vos projets en C#. Si vous décidez de continuer à utiliser IronPDF après l'essai, les licences commencent à partir de $799.

Questions Fréquemment Posées

Comment fonctionne la fonction Find en C# pour les développeurs ?

La fonction Find en C# permet aux développeurs de trouver le premier élément d'une collection, d'un tableau ou d'une liste qui satisfait des conditions spécifiques définies par un prédicat. Cette fonctionnalité est utile pour optimiser le processus de codage.

Qu'est-ce qu'un prédicat et comment est-il utilisé en C# ?

Un prédicat en C# est un délégué qui représente une méthode avec une condition spécifique. Il est utilisé dans des méthodes comme Find pour tester chaque élément d'une collection et renvoyer ceux qui répondent aux critères.

Puis-je utiliser la méthode Find avec une classe personnalisée en C# ?

Oui, vous pouvez utiliser la méthode Find avec une classe personnalisée en définissant un prédicat qui correspond aux critères de recherche des éléments de la classe, comme trouver un objet avec une valeur de propriété spécifique.

Que se passe-t-il si aucun élément ne correspond aux critères dans la méthode Find ?

Si aucun élément ne correspond aux critères spécifiés par le prédicat dans la méthode Find, elle renvoie une valeur par défaut, comme null pour les types de référence ou 0 pour les types de valeur.

Quelles sont les différences entre Find et FindAll en C# ?

La méthode Find renvoie le premier élément qui correspond au prédicat, tandis que FindAll renvoie une liste de tous les éléments qui satisfont les conditions du prédicat.

Comment les méthodes FindIndex et FindLastIndex diffèrent-elles ?

FindIndex renvoie l'indice du premier élément qui correspond au prédicat, tandis que FindLastIndex renvoie l'indice du dernier élément qui répond aux critères.

Comment puis-je intégrer une bibliothèque PDF avec C# Find pour la recherche de texte ?

En utilisant une bibliothèque PDF, vous pouvez extraire du texte des PDF et utiliser la méthode Find pour rechercher un contenu spécifique dans le texte, ce qui la rend efficace pour le traitement de documents.

Est-il possible de rechercher des éléments par leurs propriétés en utilisant Find ?

Oui, vous pouvez définir un prédicat basé sur les propriétés des éléments pour rechercher des critères spécifiques, comme localiser un objet avec un ID ou un attribut particulier.

Quelle est l'efficacité de la méthode Find pour de grandes collections de données ?

La méthode Find effectue une recherche linéaire, vérifiant chaque élément en séquence. Bien que simple, elle peut ne pas être la plus efficace pour de très grandes collections en raison de sa complexité O(n).

Quels avantages offre une bibliothèque PDF pour les développeurs C# ?

Une bibliothèque PDF offre des capacités robustes de gestion de PDF, permettant aux développeurs d'extraire, de manipuler et de rechercher facilement du contenu PDF avec C#, améliorant ainsi l'efficacité des tâches liées aux documents.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite