/** * Compare which object has a greater score. * If scores are the same, then compare by their last names. * If the last names are still the same, then compare by their first names. * * Pre-condition: * x not null * y not null * Post-condition: * return 1 if x < y * return 0 if x = y * return -1 if x > y */ public int Compare(object x, object y) { scoreRecord r1 = (scoreRecord)x; scoreRecord r2 = (scoreRecord)y; if (r2.score == r1.score) { if (r2.lastName == r1.lastName) { if (r2.firstName == r1.firstName) { return(0); } else { // second object has higher position if its name is in smaller alphabetical order return(String.Compare(r1.firstName, r2.firstName, StringComparison.OrdinalIgnoreCase)); } } else { // second object has higher position if its name is in smaller alphabetical order return(String.Compare(r1.lastName, r2.lastName, StringComparison.OrdinalIgnoreCase)); } } else { // second object has higher position if its score is higher return((r2.score > r1.score) ? 1 : -1); } }
public void CompareTestSameScoresAndLastNameDifferntFirstName() { ScoreComparer sc = new ScoreComparer(); scoreRecord higherPositionCandidate = new scoreRecord(); scoreRecord lowerPositionCandidate = new scoreRecord(); higherPositionCandidate.firstName = "ABC"; higherPositionCandidate.lastName = "XYZ"; higherPositionCandidate.score = 50; lowerPositionCandidate.firstName = "DEF"; lowerPositionCandidate.lastName = "XYZ"; lowerPositionCandidate.score = 50; Assert.IsTrue(sc.Compare(lowerPositionCandidate, higherPositionCandidate) > 0); Assert.IsTrue(sc.Compare(higherPositionCandidate, lowerPositionCandidate) < 0); Assert.IsTrue(sc.Compare(higherPositionCandidate, higherPositionCandidate) == 0); }
public void CompareTestDifferentScores() { ScoreComparer sc = new ScoreComparer(); scoreRecord higherPositionCandidate = new scoreRecord(); scoreRecord lowerPositionCandidate = new scoreRecord(); higherPositionCandidate.firstName = "ABC"; higherPositionCandidate.lastName = "XYZ"; higherPositionCandidate.score = 99; lowerPositionCandidate.firstName = "ABC"; lowerPositionCandidate.lastName = "XYZ"; lowerPositionCandidate.score = 80; Assert.IsTrue(sc.Compare(lowerPositionCandidate, higherPositionCandidate) > 0); Assert.IsTrue(sc.Compare(higherPositionCandidate, lowerPositionCandidate) < 0); Assert.IsTrue(sc.Compare(higherPositionCandidate, higherPositionCandidate) == 0); }