usingSystem;namespacelinqdemo1{classProgram {Static voidMain (string[] args) {person[] Persons= { Newperson {FirstName ="Damon", LastName ="Hill"}, Newperson {FirstName ="Niki", LastName ="Lauda"}, Newperson {FirstName ="Ayrton", LastName ="Senna"} }; Array.Sort (persons);//Now you can compare the foreach(varPinchpersons) {Console.WriteLine (P); } console.readkey (); } } classPerson:icomparable<person> { Public intCompareTo (person other) {if(Other = =NULL) { return 1; } intresult =string. Compare ( This. LastName, other. LastName); if(Result = =0) {result=string. Compare ( This. FirstName, other. FirstName); } returnresult; } Public Override stringToString () {return string. Format ("{0} {1}", FirstName, LastName); } Public stringFirstName {Get;Set; } Public stringLastName {Get;Set; } }}
But sometimes the person class is someone else's class, can not be modified, then how to do?
In this case, you can define a new class, such as: Personcomparer inheritance icomparer<person>
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;namespacelinqdemo1{classProgram {Static voidMain (string[] args) {person[] Persons= { Newperson {FirstName ="Damon", LastName ="Hill"}, Newperson {FirstName ="Niki", LastName ="Lauda"}, Newperson {FirstName ="Ayrton", LastName ="Senna"} }; Array.Sort (Persons,NewPersoncomparer (personcomparetype.firstname)); foreach(varPinchpersons) {Console.WriteLine (P); } console.readkey (); } } Public enumPersoncomparetype {FirstName, LastName} Public classPersoncomparer:icomparer<person> { PrivatePersoncomparetype Comparetype; Publicpersoncomparer (Personcomparetype comparetype) { This. Comparetype =Comparetype; } Public intCompare (person x, person y) {if(x = =NULL&& y = =NULL)return 0; if(x = =NULL)return 1; if(Y = =NULL)return-1; Switch(comparetype) { CasePersoncomparetype.firstname:return string. Compare (X.firstname, y.firstname); CasePersoncomparetype.lastname:return string. Compare (X.lastname, y.lastname); default: Throw NewArgumentException ("Unexpected Compare type"); } } } Public classPerson { Public Override stringToString () {return string. Format ("{0} {1}", FirstName, LastName); } Public stringFirstName {Get;Set; } Public stringLastName {Get;Set; } }}
The Array class also provides a sort () overload method that requires a delegate as a parameter that can be passed to the method to compare 2 objects without relying on the IComparable or IComparer interface, which means that the above is white toss, there is more advanced practice! That's the Commission!
Implement the comparator interface Icomparable<t>, and let the custom type array also be sorted