Use of c # arraylist's Sort () method

zhaozj2021-02-16  81

Keywords: arraylist, iComparer, interface, c #

I saw someone on the Internet asked the IComparer interface, so I wrote a small example and shared with everyone. There is a deficiency, I hope that I don't finish correct.

1, build a structure of an employee? Private struct EPLOYEE {??? public string? Name; ??? public int agent; ??? public string sex; ??} 2, newly built 3 "employees"? EPLOYEE EP1 = New EPLOYEE (); ?? EP1.NAME = "Small Zhang"; ?? EP1.AGE = 21; ?? EP1.SEX = "Men";? EPLOYEE EP2 = New EPLOYEEEEEE (); ?? EP2.NAME = " Lao Li "; ?? EP2.AGE = 43; ?? EP2.SEX =" Men ";? EPLOYEE EP3 = New EPLOYEEEE (); ?? EP3.NAME =" Shi "; ?? EP3.AGE = 18; ?? EP3.SEX = "Men"; 3. Add 3 "employees" to "employeelist (); ?? EMPLOYEELIST.ADD (EP2); ?? Employeelist.add (EP2 Employeelist.add (EP3);

Ok, everything is ready, now I hope that "employees" in Employeelist is sorted by age. What is it? In fact, it is very simple, we don't have to realize a certain sort method, bubble or other. ArrayList provides our ready-made sorting method sort (); it has three overloads, no matter which one is used, you want you to provide a Comparer: IComparer; to tell Sort Method You are sorting the "employee". This Comparer must implement interface: System.Collections.icomparer, only one member function needs you to implement. ? Description as follows:? [Visual Basic] Function Compare (_ ?? Byval x askA in _? B b]] j j o (?? Object x, ?? Object Y); [C ] int compare (?? Object * x, ?? Object * y); [jscript] function compare (?? x: Object, ?? Y: Object): int; (can refer to MSDN) know these let's Implement a private class myemployeecompare: system.collections.icomparer {??? public int compare (Object X, Object Y) {???? Return ((EPLOYEE) Y) .age; ???} ?????} Because we compare the "employee" AGE, we can confuse the statement? Return ((EPLOYEE) x) .age; (EPLOYEE) Y) .age

? myemployeecompare employeecompare = new myemployeecompare () ;? ok Now we can sort the "employee" ?? EmployeeElist.sort (EmployeeCompare);

#end

I have written for the second time, I hope you will support it! The above code is just a rough demo.

I hope to discuss the DOTNET technology with you. QQ: 14754875 Forum: http://www.shixm.com/bbs

转载请注明原文地址:https://www.9cbs.com/read-12607.html

New Post(0)