Home
C#
List Find and Exists Examples
This page was last reviewed on Apr 24, 2023.
Dot Net Perls
List, Find. A C# List can be searched imperatively (with a for-loop). It can be searched instead with the Find method: this often uses a lambda expression.
List
List Contains
Shows a list
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.
Predicate
Lambda
Step 1 We create a list of int elements. The list has 3 values in it upon creation.
Step 2 We call find. This code loops through each int value, starting at the beginning, and tests each one to see if it is greater than 20.
Step 3 The value 23 is returned. The parameter to the Find method is a lambda expression: a Predicate instance.
Shows a list
using System; using System.Collections.Generic; // Step 1: create the List. List<int> list = new List<int>(new int[] { 19, 23, 29 }); // Step 2: find first element greater than 20. int result = list.Find(item => item > 20); // Step 3: print result. Console.WriteLine(result);
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.
using System; using System.Collections.Generic; 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);
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.
Here The FindIndex call finds the first element greater than or equal to 100. This is 700, which is at the index 2.
Return If the element is not found, the special value -1 is returned. We must test for this value in most code that uses FindIndex.
using System; using System.Collections.Generic; 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);
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.
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.
String StartsWith
Console.WriteLine
using System; using System.Collections.Generic; var list = new List<string>() { "bird", "frog", "ball", "leaf" }; // Invoke FindAll in foreach. // ... 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); }
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.
Info The code tests first to see if any element in the List exists that has a value greater than 10, which returns true.
Then The code tests for values less than 7, which returns false. We can see that Exists returns true or false.
true, false
using System; using System.Collections.Generic; 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);
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).
for
foreach
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 24, 2023 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.