#151 – Determining Whether an Array Contains a Specific Element

You can use the Array.Find method to find a particular element in an array.  If, however, you only care whether a particular element is present in an array, you can use the IEnumerable.Contains method.  The Contains method returns true if the element was found in the array, false if not.

            int[] scores = { 89, 98, 72, 100, 83 };

            bool someoneAcedIt = scores.Contains(100);   // true

Contains also works on arrays holding objects belonging to a custom type.

            Person[] folks = new Person[3];
            folks[0] = new Person("Bronte", "Emily", 29);
            folks[1] = new Person("Bronte", "Charlotte", 31);
            folks[2] = new Person("Tennyson", "Alfred", 24);

            bool foundAlfred = folks.Contains(new Person("Tennyson", "Alfred", 24));

This will only work as expected if the underlying type has implemented the equality operator in a way that properly compares two objects to determine if they are equal.  If the equality operator has not been defined, only the references to the objects will be compared, rather than the contents of the objects.

Advertisement

#101 – Use Contains() to Discover If A String Contains Other Strings

You can use String.IndexOf to search for a substring within another stringIndexOf returns a 0-based index of the string that you’re searching for.

But if you don’t care about the location of the substring and just want to know whether it’s contained in the larger string, you can use the String.Contains method.  You can also search for individual characters.  Note that the search is case sensitive.

 string s = "A man, a plan, a canal";
 bool b = s.Contains("canal");   // true
 b = s.Contains("Canal");        // false (case-sensitive)
 b = s.Contains('p');            // true

You can also search for a particular substring at the start or the end of a string.

string s = "Call me Ishmael";
 bool b = s.StartsWith("me");       // false
 b = s.EndsWith("Ishmael");         // true
 b = s.StartsWith("Call");          // true