Check If a Value Is in an Array in C#



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
Updated on: 2020-06-22T13:59:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements