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.

138 ❘ ChaPTer 6 ArrAys And tuples<br />

should be compared. The IComparer interface is independent of the class to compare. That’s why the<br />

Compare() method defines two arguments that should be compared. The return value is similar to the<br />

CompareTo() method of the IComparable interface.<br />

The class PersonComparer implements the IComparer interface to sort Person objects either by<br />

firstName or by lastName The enumeration PersonCompareType defines the different sorting options<br />

that are available with the PersonComparer: FirstName <strong>and</strong> LastName. How the compare should happen<br />

is defined with the constructor of the class PersonComparer where a PersonCompareType value is set. The<br />

Compare() method is implemented with a switch statement to compare either by LastName or<br />

by FirstName.<br />

public enum PersonCompareType<br />

{<br />

FirstName,<br />

LastName<br />

}<br />

public class PersonComparer: IComparer<br />

{<br />

private PersonCompareType compareType;<br />

public PersonComparer(PersonCompareType compareType)<br />

{<br />

this.compareType = compareType;<br />

}<br />

public int Compare(Person x, Person y)<br />

{<br />

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

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

}<br />

}<br />

switch (compareType)<br />

{<br />

case PersonCompareType.FirstName:<br />

return x.FirstName.CompareTo(y.FirstName);<br />

case PersonCompareType.LastName:<br />

return x.LastName.CompareTo(y.LastName);<br />

default:<br />

throw new ArgumentException(<br />

"unexpected compare type");<br />

}<br />

code snippet SortingSample/PersonComparer.cs<br />

Now you can pass a PersonComparer object to the second argument of the Array.Sort() method. Here<br />

the persons are sorted by first name:<br />

Array.Sort(persons,<br />

new PersonComparer(PersonCompareType.FirstName));<br />

foreach (var p in persons)<br />

{<br />

Console.WriteLine(p);<br />

}<br />

code snippet SortingSample/Program.cs<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!