First define the comparison class inherits from Icomparer<racer>
1 Public classRacercomparer:icomparer<racer>2 {3 Public enumComparetype4 {5 FirstName, LastName, country, Wins6 }7 PrivateComparetype Comparetype;8 Publicracercomparer (comparetype comparetype)9 {Ten This. Comparetype =Comparetype; One } A Public intCompare (Racer x, Racer y) - { - if(x = =NULL&& y = =NULL)return 0; the if(x = =NULL)return-1; - if(Y = =NULL)return 1; - - intresult; + Switch(Comparetype) - { + CaseComparetype.firstname: A return string. Compare (X.firstname, y.firstname); at CaseComparetype.lastname: - return string. Compare (X.lastname, y.lastname); - CaseComparetype.country: -result =string. Compare (X.country, y.country); - if(Result = =0) - return string. Compare (X.lastname, y.lastname); in Else - returnresult; to CaseComparetype.wins: + returnX.wins.compareto (y.wins); - default: the Throw NewArgumentException ("Invalid Compare Type"); * } $ }Panax Notoginseng}
View Code
1 classRacer:icomparable<racer>2 {3 Public intId {Get;Private Set; }4 Public stringFirstName {Get;Set; }5 Public stringLastName {Get;Set; }6 Public stringCountry {Get;Set; }7 Public intWins {Get;Set; }8 Public Override stringToString ()9 {Ten returnString.Format ("{0} {1}", FirstName, LastName); One } A PublicRacer (intIdstringFirstName,stringLastName,stringcountry) -: This(ID, FirstName, lastName, country, wins:0) - { the } - PublicRacer (intIdstringFirstName,stringLastName,stringCountry,intwins) - { - This. Id =ID; + This. FirstName =FirstName; - This. LastName =LastName; + This. Country =Country; A This. Wins =wins; at } - Public intCompareTo (Racer other) - { - if(Other = =NULL)return-1; - intCompare =string. Compare ( This. LastName, other. LastName); - if(Compare = =0) in return string. Compare ( This. FirstName, other. FirstName); - returnCompare; to } +}
View Code
Call comparison method
1 varGraham =NewRacer (7,"Graham","Hill","UK", -);2 varEmerson =NewRacer ( -,"Emerson","Fittipaldi","Brazil", -);3 varMario =NewRacer ( -,"Mario","Andretti","USA", A);4 5 varRacers =NewList<racer> ( -) {Graham, Emerson, Mario};6Racers. Sort (NewRacercomparer (RacerComparer.CompareType.Country));
View Code
C # overriding IComparer interface