C# List Exists, Use Lambda to SearchThis C# example program uses the Exists method on the List type. Exists uses a lambda to search a list.
returns whether a List element is present. You could use a loop and an if-statement. But the Exists method may be clearer in some program contexts. We invoke this method with a lambda expression.List
We examine the Exists method on List. This is an instance method that returns true or false depending on whether any element matches the Predicate parameter. The Predicate is a method that returns true or false when passed each element.Predicate
Lambda: We use Exists to search for an element based on a lambda. The lambda matches the signature for a Predicate.Lambdas
C# program that uses Exists method on List
static void Main()
List<int> list = new List<int>();
// See if any elements with values greater than 10 exist.
bool exists = list.Exists(element => element > 10);
// Check for numbers less than 7.
exists = list.Exists(element => element < 7);
The code tests first to see if any element in the List exists that has a value greater than 10, which returns true. Then it tests for values less than 7, which returns false.
Tip: You can also see the Find method in a separate article. It can be used in many program contexts.Find
Summary. In this example, we looked at the Exists instance method on the List type in the C# language and .NET Framework. As a quick way to determine if an element exists, the Exists method is useful in many programs.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.