#147 – Getting the Average of an Array of Numbers

If you have an array containing a collection of numeric values, you can get the average (mean) using the Average method.

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

            double avg = scores.Average();      // 88.4

The Average method is an extension method, applied to Array by virtue of its implementation of the IEnumerable interface.  It’s part of the System.Linq namespace, so you’ll need a using statement for this namespace.  Average is available in .NET 4 and 3.5.

Average will work for arrays containing any numeric type.

#140 – Making a Deep Copy of an Array Using an Object’s Clone Method

When you use the Array.Clone method of an array to make a copy of an array that contains instances of a reference type, you get a shallow copy–the new array references the same underlying objects as the original array.

A deep copy of an array is one in which you create a new copy of each element, so that the new array references different objects.

You can possibly make a deep copy if the element type has a Clone method.

            // Shallow copy of the array
            Person[] folks2 = (Person[])folks1.Clone();

            // Deep copy by calling Clone method on each element
            Person[] folks3 = new Person[folks1.Length];
            for (int i = 0; i < folks1.Length; i++)
                folks3[i] = (Person)folks1[i].Clone();

We’re now calling Clone on each element, rather than on the array itself.

This method doesn’t guarantee a deep copy, since there’s no guarantee that Person.Clone will give us a deep copy of Person.

#138 – Searching a Sorted Array

If an array is already sorted and if the type that its elements belong to has implemented IComparable, you can use the BinarySearch method to quickly search for a particular element.

Using our earlier example, with a Person class that implements IComparable (sorts by LastName/FirstName), we can search for a particular Person in a sorted array:

            Person[] folks = new Person[4];
            folks[0] = new Person("Bronte", "Emily");
            folks[1] = new Person("Bronte", "Charlotte");
            folks[2] = new Person("Tennyson", "Alfred");
            folks[3] = new Person("Mailer", "Norman");

            // Sort
            Array.Sort(folks);    // C. Bronte, E. Bronte, Mailer, Tennyson

            // Now search - returns index of 2 (3rd element)
            int normIndex = Array.BinarySearch(folks, new Person("Mailer", "Norman"));
            Person norm = folks[normIndex];     // Get reference to Normal

If you have a property not used for sorting purposes (e.g. Person.Age), you can’t be guaranteed that the object returned as a match actually matches your specified object–for that property.  Only properties used for comparison are guaranteed to match in the object returned.