C# List<T> class provides methods and features to construct a list of objects. It contains a process by which it checks whether a particular item already exists or not in the list.

List<T>.Find(Predicate<T>) Method

Definition:

It searches for an element that matches the conditions defined by specific parameters and returns the first occurrence of that element from the entire List.

public T? Findlist (Predicate<T> match);

Parameters:

The Predicate<T> element is responsible for assigning and defining the conditions for the element we are looking for.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Returns:

This returns the first element that matches the element we are looking for; otherwise, it will show the default value. 

Exceptions:

The exception is thrown when a null reference is passed to the method or class that does not accept it. 

Example:

The following example contains the example of a list find method.

using System;

using System.Collections.Generic;

// Simple business object. A PartId is used to identify a part

public class Part : IEquate<Part>

{

    public string Partname { get; set; }

    public int PartId { get; set; }

    public override string ToString()

    {

        return "ID: " + PartId + "   Name: " + Partname;

    }

    public override bool Equals(object obj)

    {

        if (obj == null) return false;

        Part objAsPart = obj as Part;

        if (objAsPart == null) return false;

        else return Equals(objAsPart);

    }

    public override int GetHashCode()

    {

        return PartId;

    }

    public bool Equals(Part other)

    {

        if (other == null) return false;

        return (this.PartId.Equals(other.PartId));

    }

    // Should also override == and != operators.

}

public class Example

{

    public static void Main()

    {

        // Create a list of parts.

        List<Part> parts = new List<Part>();

        // Add parts to the list.

        parts.Add(new Part() { Partname = "crank arm", PartId = 1234 });

        parts.Add(new Part() { Partname = "chain ring", PartId = 1334 });

        parts.Add(new Part() { Partname = "regular seat", PartId = 1434 });

        parts.Add(new Part() { Partname = "banana seat", PartId = 1444 });

        parts.Add(new Part() { Partname = "cassette", PartId = 1534 });

        parts.Add(new Part() { Partname = "shift lever", PartId = 1634 }); ;

        // Write out the parts in the list. This will call the overridden ToString method

        // in the Part class.

        Console.WriteLine();

        foreach (Part aPart in parts)

        {

            Console.WriteLine(aPart);

        }

        // Check the list for part #1734. This calls the IEquate.Equals method

        // of the Part class, which checks the PartId for equality.

        Console.WriteLine("\nContains: Part with Id=1734: {0}",

            parts.Contains(new Part { PartId = 1734, PartName = "" }));

        // Find items where the name contains "seat".

        Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",

            parts.Find(x => x.PartName.Contains("seat")));

        // Check if an item with Id 1444 exists.

        Console.WriteLine("\nExists: Part with Id=144: {0}",

            parts.Exists(x => x.PartId == 144));

        /*This code example produces the following output:

        ID: 1234   Name: crank arm

        ID: 1334   Name: chain ring

        ID: 1434   Name: regular seat

        ID: 1444   Name: banana seat

        ID: 1534   Name: cassette

        ID: 1634   Name: shift lever

        Contains: Part with Id=174: False

        Find: Part where name contains "seat": ID: 1434   Name: regular seat

        Exists: Part with Id=144: True

         */

    }

}

Become a Certified UI UX Expert in Just 5 Months!

With The Best-in-class UI UX ProgramExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Other Methods  

1. Using Enumerable.Contains() Method (System.Linq)

This method helps to understand whether a specific element is present or not in a simple and easy-to-understand manner. An example of this method is provided below:

using System;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target) {

        return list.Contains(target);

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4};

        int target = 4;

 

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the given list");

        }

        else {

            Console.WriteLine("Element does not found in the given list");

        }

    }

}

2. Using List.IndexOf() Method

This method returns the index of the first occurrence of the specified element in this list and otherwise returns -1 if no element is found.

using System;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target) {

        return list.IndexOf(target) != -1;

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4 };

        int target = 4;

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the given list");

        }

        else {

            Console.WriteLine("Element does not found in the given list");

        }

    }

}

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

3. Using List.FindIndex() Method

This method returns the occurrence of the first element mentioned in the predicate and returns -1 if no element satisfies the condition.

using System;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target) {

        return list.FindIndex(x => x.Equals(target)) != -1;

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4 };

        int target = 3;

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the given list");

        }

        else {

            Console.WriteLine("Element does not found in the given list");

        }

    }

}

4. Using List.FindAll() Method

This method returns the list of all the elements which match the given specified conditions. We can use it to check the existence of the element from this list.

using System;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target)

    {

        List<T> results = list.FindAll(x => x.Equals(target));

        return results.Count > 0;

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4};

        int target = 2;

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the list");

        }

        else {

            Console.WriteLine("Element not found in the given list");

        }

    }

}

5. Using Enumerable.Where() Method (System.Linq)

This method is used to filter a sequence of values based on the provided predicate. 

Example:

using System;

using System.Linq;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target)

    {

        try {

            list.Where(i => i.Equals(target)).First();

            // or

            // list.First(i => i.Equals(target));

            // or

            // list.Single(i => i.Equals(target));

            return true;

        }

        catch (InvalidOperationException) {

            return false;

        }

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4};

        int target = 2;

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the list");

        }

else {

            Console.WriteLine("Element not found in the given list");

        }

    }

}

6. Perform a Linear Search

A naive solution would be to do a linear search to find the element specified in the predicate.

using System;

using System.Collections.Generic;

public static class Extension

{

    public static bool find<T>(this List<T> list, T target)

    {

        EqualityComparer<T> comparer = EqualityComparer<T>.Default;

        foreach (T i in list)

        {

            if (comparer.Equals(i, target)) {

                return true;

            }

        }

        return false;

    }

}

public class Sample

{

    public static void Main()

    {

        List<int> list = new List<int> { 1, 2, 3, 4};

        int target = 1;

        bool isExist = list.find(target);

        if (isExist) {

            Console.WriteLine("Element found in the list");

        }

        else {

            Console.WriteLine("Element not found in the given list");

        }

    }

}

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, we learned about the c# list find method and how it is useful for finding an element in a list. We discussed how this method returns the first occurrence of the element when found and otherwise returns the given values; processing and searching of elements stops once the element is found.

If you are interested in learning more about more about C# and other related concepts of C#, you can enroll in Simplilearn’s exclusive full-stack web development certification course and accelerate your career as a software developer through this Post Graduate Program in Full Stack Web Development course.

Also in case you are not prepared for the certification course yet, Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. You can take up any of these courses to upgrade your skills and advance your career.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449