Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to check if a value is in an array
Use the Array.Exists method to check if a value is in an array or not. This method returns a boolean value indicating whether the specified element exists in the array.
Syntax
Following is the syntax for Array.Exists method −
public static bool Exists<T>(T[] array, Predicate<T> match)
Parameters
-
array − The one-dimensional array to search.
-
match − A predicate that defines the conditions of the element to search for.
Return Value
Returns true if the array contains an element that matches the conditions defined by the specified predicate; otherwise, false.
Using Array.Exists with Lambda Expression
The most common way to use Array.Exists is with a lambda expression to define the search condition −
Example
using System;
public class Demo {
public static void Main() {
string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger"};
bool res1 = Array.Exists(strArray, ele => ele == "harddisk");
Console.WriteLine("harddisk exists: " + res1);
bool res2 = Array.Exists(strArray, ele => ele == "keyboard");
Console.WriteLine("keyboard exists: " + res2);
}
}
The output of the above code is −
harddisk exists: False keyboard exists: True
Using Array.Exists with Different Data Types
Example
using System;
public class Demo {
public static void Main() {
int[] numbers = {10, 20, 30, 40, 50};
bool hasEven = Array.Exists(numbers, n => n % 2 == 0);
Console.WriteLine("Array contains even number: " + hasEven);
bool hasGreaterThan35 = Array.Exists(numbers, n => n > 35);
Console.WriteLine("Array contains number > 35: " + hasGreaterThan35);
bool hasNegative = Array.Exists(numbers, n => n
The output of the above code is −
Array contains even number: True
Array contains number > 35: True
Array contains negative number: False
Using Array.Exists with Custom Objects
Example
using System;
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) {
Name = name;
Age = age;
}
}
public class Demo {
public static void Main() {
Person[] people = {
new Person("John", 25),
new Person("Alice", 30),
new Person("Bob", 22)
};
bool hasAlice = Array.Exists(people, p => p.Name == "Alice");
Console.WriteLine("Alice exists: " + hasAlice);
bool hasAdult = Array.Exists(people, p => p.Age >= 21);
Console.WriteLine("Adult exists: " + hasAdult);
}
}
The output of the above code is −
Alice exists: True
Adult exists: True
Conclusion
The Array.Exists method provides an efficient way to check if a value exists in an array using a predicate function. It works with any data type and allows flexible search conditions using lambda expressions, making it ideal for both simple value checks and complex object searches.
