.NET HELP

C# Find (How It Works For Developers)

Published June 13, 2023
Share:

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; }

    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 OrElse 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#

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:


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#

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:


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#

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:


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#

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#

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;

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#

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, 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 $749.

< PREVIOUS
C# Types (How It Works For Developers)
NEXT >
C# New (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >