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

CsharpProgrammingServer Side Programming

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
raja
Published on 20-Aug-2018 13:24:09
Advertisements