HomeSearch

C# List Find and Exists Examples

Invoke the Find and Exists method on the List type to search Lists with lambda expressions.
List, Find. A list can be searched imperatively (with a for-loop). It can be searched instead with the Find method: this often uses a lambda expression.ListList Contains
Other methods. Exists() is just like Find on List except it returns true or false, not a new List of matches. It can make some code simpler. Find() and Exists() makes some C# code clearer.
Find example. Here we consider the Find() method on List. Find accepts a Predicate, which we can specify as a lambda expression. It returns the first match.PredicateLambda

Here: This code loops through each int value in the List, starting at the beginning, and tests each one to see if it is greater than 20.

Return: The value 23 is returned. The parameter to the Find method is a lambda expression: a Predicate instance.

C# program that uses Find method on List using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(new int[] { 19, 23, 29 }); // Finds first element greater than 20 int result = list.Find(item => item > 20); Console.WriteLine(result); } } Output 23
FindLast. To search backwards, use the FindLast method. FindLast will scan the List from the last element to the first. Here we use FindLast instead of Find.
C# program that uses FindLast using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<int>(new int[] { 19, 23, 29 }); // Find last element greater than 20. int result = list.FindLast(item => item > 20); Console.WriteLine("FINDLAST: {0}", result); } } Output FINDLAST: 29
FindIndex. There are also FindIndex and FindLastIndex methods. FindIndex returns the index of the first matching element, starting its search from the first element.

Example: The FindIndex call here finds the first element greater than or equal to 100. This is 700, which is at the index 2.

Not found: If the element is not found, the special value -1 is returned. We must test for this value in most code that uses FindIndex.

C# program that uses FindIndex using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<int>() { 0, 1, 700, 0 }; // Find index of element 100 or greater. int result = list.FindIndex(element => element >= 100); Console.WriteLine("FINDINDEX: {0}", result); } } Output FINDINDEX: 2
FindAll. We can also call the FindAll method. FindAll() returns a modified List of the same element type as the original List. It also receives a Predicate.

Program: Here we invoke FindAll in a foreach-loop condition. FindAll is only called once at the start of the foreach-loop.

Result: We match all strings starting with the lowercase "b," and print them to the console in the body of the loop.

StartsWith, EndsWithConsole
C# program that invokes FindAll using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<string>() { "bird", "frog", "ball", "leaf" }; // Invoke FindAll info reach. // ... FindAll is only invoked once for the entire loop. foreach (string value in list.FindAll(element => element.StartsWith("b"))) { Console.WriteLine("FINDALL, STARTSWITH B: {0}", value); } } } Output FINDALL, STARTSWITH B: bird FINDALL, STARTSWITH B: ball
Exists. We examine the Exists method on List. Exists returns whether a List element is present. We invoke this method with a lambda expression.

Exists call 1: The code tests first to see if any element in the List exists that has a value greater than 10, which returns true.

Exists call 2: Then it tests for values less than 7, which returns false. We can see that Exists returns true or false.

True, False
C# program that uses Exists method on List using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(7); list.Add(11); list.Add(13); // See if any elements with values greater than 10 exist. bool exists = list.Exists(element => element > 10); Console.WriteLine(exists); // Check for numbers less than 7. exists = list.Exists(element => element < 7); Console.WriteLine(exists); } } Output True False
Loops. When the iteration logic is important, we can use for and foreach loops with List. Using loops is usually faster than invoking delegates (like the Predicate arguments to Find).ForForeach
A summary. A List can be searched with built-in methods and lambda expressions. These methods are convenient and fast. They can help us place the emphasis on other logic in the program.
Summary, continued. Exists() is a quick way to determine if a matching element is present. Exists() and find() may not be the fastest searching methods, but they are clear and often useful.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.