How to check if an item exists in a C# array?


Use the Equals method to check if an item exists in a C# array.

Set string and substring −

string subStr = "pqrs";
string[] str = {
   "abcd",
   "ijkl",
   "pqrs",
   "wxyz"
};

Now check whether the substring is part of the string or not using the Equals method.

if (item.Equals(subStr)) {
   Console.WriteLine("Item Found");
}

Here is the complete code −

Example

 Live Demo

using System;
namespace Program {
   public class Demo {

      public static void Main(String[] args) {
         string subStr = "pqrs";
         string[] str = {
            "abcd",
            "ijkl",
            "pqrs",
            "wxyz"
         };

         foreach(string item in str) {
            if (item.Equals(subStr)) {
               Console.WriteLine("Item Found");
            }
         }
      }
   }
}

Output

Item Found

Updated on: 22-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements