I want to sort a list of people
list & lt; Person & gt; Person = new list & lt; Person & gt; (); person. Add (New Person ("John", "Barnald", 45000.89)); person. Add (new person ("Mark", "Drake", 346.89)); person. Add (new person ("Bill", "Watts", 456.8 99));
Public Enum Comparison Option {P> How to go sorting using lambda expression What is it?
Public Stable List & lt; Person & gt; Sort People (this list & lt; person & gt; lst, compare option opt1, sort order order) {lst.Sort ((p, op1, op2) => {lambda expression can be implemented here} ); }
It looks like you call the sort method on list & lt Trying to; T & gt;
which is a comparison & lt; T & gt;
Represents. This will require little work because you have to first define a consistent comparison function
The first step is to select comparison option
value
private Stable comparison & lt; Person & gt; To write a comparison function on the basis of. Create (Compare Optimization Opt) {switch (opt) {Case comparison option. Byfirst debit: (x, y) => X.FirstName.CompareTo (y.FirstName); Compare matter option. Child name: (x, y) => X.LastName.CompareTo (y.LastName); Compare the caseFeatures Bilassari: (x, y) = & gt; X Salary - Y. Salari; Default: throw a new exception (); }}
By default this task will be sorted in ascending order. If you want it to fall, then just deny the price. So now the sorting people can be written by following
public static list & lt; Person & gt; Sort People (this list & lt; person & gt; list, compare option opt1, sort order order)) Original Origin = Create (opt 1); Var comp = Original; If (ord == SortOrder.Descending) {comp = (x, y) = & gt; - (Original (X, Y)); } List.Sort (COMP); } Edit version that is 100% done in Lambda
& Lt; Person & gt; Sort People (this list & gt; person & gt; list, comparison option opt1, sort order order)) list. Abstract ((x, y) => {int comp = 0; switch (opt) {Compare matter comparison (y.FirstName); Compare case attributes: BellName: comp = x.ListName.CompareTo (y .LastName); Compare the caseFeatures: Biosari: COMP = x.Salary.CompareTo (y.Salary); Default: throw a new exception ();} If (ord == SortOrder.Descending) {comp = -comp;} return Comp;}); }
No comments:
Post a Comment