TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# List Exists Method

This C# example program demonstrates the Exists method on the List type.

Exist returns whether a List element is found.

You could use a loop and an if-statement. But the Exists method may be clearer in some program contexts. We invoke the Exists method on the List type with a lambda expression.

Example. 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.

Tip: More detailed material on the Predicate type is available. This will help with many methods besides Exists.

Predicate Type

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

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.

Tip: You can also see the Find method in a separate article. It can be used in many program contexts.

List Find Method

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf