15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

array Class ❘ 137<br />

The output of the application shows the sorted result of the array:<br />

Beyonce<br />

Christina Aguilera<br />

Gwen Stefani<br />

Shakira<br />

If you are using custom classes with the array, you must implement the interface IComparable. This<br />

interface defines just one method, CompareTo(), that must return 0 if the objects to compare are equal, a<br />

value smaller than 0 if the instance should go before the object from the parameter, <strong>and</strong> a value larger than<br />

0 if the instance should go after the object from the parameter.<br />

Change the Person class to implement the interface IComparable. The comparison is done on the<br />

value of the LastName. Because the LastName is of type string, <strong>and</strong> the String class already implements<br />

the IComparable interface, with the implementation you can rely on the CompareTo() method of the<br />

String class. If the LastName has the same value, the FirstName is compared:<br />

public class Person: IComparable<br />

{<br />

public int CompareTo(Person other)<br />

{<br />

if (other == null) throw new ArgumentNullException("other");<br />

int result = this.LastName.CompareTo(<br />

other.LastName);<br />

if (result == 0)<br />

{<br />

result = this.FirstName.CompareTo(<br />

other.FirstName);<br />

}<br />

return result;<br />

}<br />

//...<br />

code snippet SortingSample/Person.cs<br />

Now it is possible to sort an array of Person objects by the last name:<br />

Person[] persons = {<br />

new Person { FirstName="Damon", LastName="Hill" },<br />

new Person { FirstName="Niki", LastName="Lauda" },<br />

new Person { FirstName="Ayrton", LastName="Senna" },<br />

new Person { FirstName="Graham", LastName="Hill" }<br />

};<br />

Array.Sort(persons);<br />

foreach (var p in persons)<br />

{<br />

Console.WriteLine(p);<br />

}<br />

Using the sort of the Person class, the output returns the names sorted by the last name:<br />

Damon Hill<br />

Graham Hill<br />

Niki Lauda<br />

Ayrton Senna<br />

code snippet SortingSample/Program.cs<br />

If the Person object should be sorted differently, or if you don’t have the option to change the class that<br />

is used as an element in the array, you can implement the interface IComparer or IComparer. These<br />

interfaces define the method Compare(). One of these interfaces must be implemented by the class that<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!