
Exist returns whether a List element is found. Although you could use a loop and an if-statement, the Exists method may be clearer in some program contexts. In this example, we invoke the Exists method on the List type with a lambda expression.
Lambda ExpressionThis C# example program demonstrates the Exists method on the List type.
Here we see the Exists method on List, which 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 TypeProgram that uses Exists method on List [C#]
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
Description. The example for Exists above 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. You can also see the Find method in a separate article.
List Find Method
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 different programs.
Collections