Find An Item In List Using LINQ - C#

Sameer Saini March 02, 2022
Find An Item In List Using LINQ - C#

Have you been in a situation where you have a list and you have to find an item in the list?

C# offers us an easy way to find an item in a list using the .Find() method.

The Find() method searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List.

 

Syntax - List.Find(Predicate) Method

public T? Find (Predicate match)

Parameters: The Find method takes a predicate delegate that defines the conditions of the elements to search for.

Returns: The first element that matches the condition (if any) defined by the perdicate. If there is no match, the default value for type returned.

 

Let's Understand How To Find An Item In List - Code Example

Let's say we have an object "Employee"

public class Employee { public int Id { get; set; } public string Name { get; set; } public double Salary { get; set; } public bool Active { get; set; } }

Let's create some data for this list.

var employees = new List() { new Employee() { Id = 1, Name = "John" , Active = true , Salary= 10000}, new Employee() { Id = 2, Name = "Julie" , Active = false , Salary= 15000}, new Employee() { Id = 3, Name = "Sachin" , Active = true , Salary= 20000}, new Employee() { Id = 3, Name = "Tim" , Active = false , Salary= 25000} };

Now, in this list, we will use the .Find() method and find the employee which matches the criteria.

Criteria 1: Find an employee with a salary more than 10000

var findEmployee = employees.Find(x => x.Salary > 10000); if (findEmployee != null) Console.WriteLine(findEmployee.Name);

Output:

Julie

Criteria 2: Find an employee with a salary more than 10000 and Active = true

var findEmployee = employees.Find(x => x.Salary > 10000 && x.Active == true); if (findEmployee != null) Console.WriteLine(findEmployee.Name);

Output:

Sachin

Criteria 3: Find an employee with salary less than 5000

var findEmployee = employees.Find(x => x.Salary < 5000); if (findEmployee != null) Console.WriteLine(findEmployee.Name); else Console.WriteLine("No employees match the criteria.");

Output:

No employees match the criteria.