#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: