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.

Set a string array −

string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" };

Let’s say you need to find the value “keyboard” in the array. For that, use Array.Exists() −

Array.Exists(strArray, ele => ele == "keyboard");

It returns a true value if element exists as shown below −

Example

 Live Demo

using System;
using System.Text;
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(res1);
      bool res2 = Array.Exists(strArray, ele => ele == "keyboard");
      Console.WriteLine(res2);
   }
}

Output

False
True

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

852 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements