The Exists property is a very useful property in C#, which checks whether any element in the collection meets a given condition. This property is part of the List
The Exists property is a Boolean property defined in the C# List
public bool Exists(Predicatematch)
Let's see an example that demonstrates how to use the Exists property to check if any element exists in a list.
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { Listfruits = new List () { "apple", "banana", "orange", "grape", "mango" }; bool exists = fruits.Exists(f => f.Equals("apple")); if (exists) { Console.WriteLine("Apple exists in the list"); } else { Console.WriteLine("Apple does not exist in the list"); } } }
In this code, we have a list of strings called fruits. We use the Exists property to check if the element "apple" exists in the list. We pass a lambda expression that checks if each element in the list is equal to "apple".
Apple exists in the list
Now, let's look at an example that demonstrates how to use the Exists property to check if any element in the list satisfies a condition.
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { Listnumbers = new List () { 1, 2, 3, 4, 5 }; bool exists = numbers.Exists(n => n > 3); if (exists) { Console.WriteLine("There exists an element in the list greater than 3"); } else { Console.WriteLine("There is no element in the list greater than 3"); } } }
In this code, we have a list of integers called numbers. We use the Exists property to check if any element in the list is greater than 3. We passed a lambda expression that checks if each element in the list is greater than 3.
There exists an element in the list greater than 3
The Exists property is a powerful property that can be used to check whether any element in the collection meets a given condition. In this article, we explored the usage of Exists property in C# programs. We saw how to check if an element exists in a list, and how to check if any element in the list satisfies a condition.
The above is the detailed content of C# program shows the use of Exists property. For more information, please follow other related articles on the PHP Chinese website!