Topic description
Different methods find whether an element exists in an array. (console application)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace find array element { class Program { static void Main(string[] args) { int[] myintArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6 }; int result; //IndexOf(parameter 1, parameter 2) parameter 1 is the data to be found, parameter 2 is the element to be found //It is often used to judge whether there is an element in the array, return the index value if it exists, and return -1 if it does not exist result = Array.IndexOf(myintArray,8); if(result<0) Console.WriteLine("The element does not exist in the array"); else Console.WriteLine("Find the element"); Console.WriteLine("The index value of the first occurrence of 5 is {0}, and the index value of the last occurrence is {1}", Array.IndexOf(myintArray,5),Array.LastIndexOf(myintArray,5)) ; Console.WriteLine(); //BinarySearch is used to find the index value of the first occurrence of the element. The method used is called dichotomy. If the element is not stored, a negative value is returned. int result2 = Array.BinarySearch(myintArray, 28); Console.WriteLine(result2); Console.WriteLine(); //Array's Contains method is actually an implementation of the IList interface, so you need to convert the array to this object before using it //Converted format: ((System.Collections.IList)myintArray).Contains(8) //returns a boolean value bool mybool; mybool=((System.Collections.IList)myintArray).Contains(8); if(mybool) Console.WriteLine("The element exists"); else Console.WriteLine("Does not exist"); } } }