Saltar al pie de página
.NET AYUDA

Buscar en C# (Cómo funciona para desarrolladores)

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.

Preguntas Frecuentes

¿Cómo funciona la función Buscar de C# para los desarrolladores?

La función Buscar de C# permite a los desarrolladores localizar el primer elemento en una colección, matriz o lista que cumpla condiciones específicas definidas por un predicado. Esta función es útil para optimizar el proceso de codificación.

¿Qué es un predicado y cómo se utiliza en C#?

Un predicado en C# es un delegado que representa un método con una condición específica. Se usa en métodos como Buscar para probar cada elemento en una colección, devolviendo aquellos que cumplen los criterios.

¿Puedo usar el método Buscar con una clase personalizada en C#?

Sí, puedes usar el método Buscar con una clase personalizada definiendo un predicado que coincida con los criterios de búsqueda para los elementos de la clase, como encontrar un objeto con un valor de propiedad específico.

¿Qué sucede si ningún elemento coincide con los criterios en el método Buscar?

Si ningún elemento coincide con los criterios especificados por el predicado en el método Buscar, devuelve un valor por defecto, como null para tipos de referencia o 0 para tipos de valor.

¿Cuáles son las diferencias entre Buscar y BuscarTodo en C#?

El método Buscar devuelve el primer elemento que coincide con el predicado, mientras que BuscarTodo devuelve una lista de todos los elementos que satisfacen las condiciones del predicado.

¿Cómo difieren los métodos BuscarÍndice y BuscarÚltimoÍndice?

BuscarÍndice devuelve el índice del primer elemento que coincide con el predicado, mientras que BuscarÚltimoÍndice devuelve el índice del último elemento que coincide con los criterios.

¿Cómo puedo integrar una biblioteca PDF con Buscar de C# para buscar texto?

Al utilizar una biblioteca PDF, puedes extraer texto de PDFs y utilizar el método Buscar para buscar contenido específico dentro del texto, haciéndolo efectivo para el procesamiento de documentos.

¿Es posible buscar elementos por sus propiedades usando Buscar?

Sí, puedes definir un predicado basado en las propiedades de los elementos para buscar criterios específicos, como localizar un objeto con un ID o atributo particular.

¿Qué tan eficiente es el método Buscar para colecciones de datos grandes?

El método Buscar realiza una búsqueda lineal, verificando cada elemento secuencialmente. Aunque sencillo, puede no ser el más eficiente para colecciones muy grandes debido a su complejidad O(n).

¿Qué beneficios ofrece una biblioteca PDF para los desarrolladores de C#?

Una biblioteca PDF proporciona capacidades robustas de manejo de PDF, lo que permite a los desarrolladores extraer, manipular y buscar contenido PDF fácilmente usando C#, mejorando así la eficiencia de las tareas relacionadas con documentos.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más