C# program to check if a value is in an array

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 12:19:08
Advertisements