C# - Sorting using Extension Method

前端 未结 4 982
野趣味
野趣味 2021-02-08 06:41

I want to sort a list of person say

List persons=new List();
persons.Add(new Person(\"Jon\",\"Bernald\",45000.89));
persons.Add(new P         


        
4条回答
  •  被撕碎了的回忆
    2021-02-08 07:46

    It looks like you are attempting to call the Sort method on List which takes a Comparison delegate. This will require a bit of work because you first have to define a compatible comparison function.

    First step is to write a comparison function based on the CompareOptions value

    private static Comparison Create(CompareOptions opt) {
      switch (opt) {
        case CompareOptions.ByFirstName: (x,y) => x.FirstName.CompareTo(y.FirstName);
        case CompareOptions.ByLastName: (x,y) => x.LastName.CompareTo(y.LastName);
        case CompareOptions.BySalary: (x,y) => x.Salary - y.Salary;
        default: throw new Exception();
      }
    }
    

    By default this function will sort in ascending order. If you want it to be descending simply negate the value. So now writing SortPeople can be done by the following

    public static List SortPeople(
       this List list, 
       CompareOptions opt1,
       SortOrder ord) )
       var original = Create(opt1);
       var comp = original;
       if( ord == SortOrder.Descending ) {
         comp = (x,y) => -(orig(x,y));
       }
       list.Sort(comp);
    }
    

    EDIT

    Version which is done 100% in a lambda

    public static List SortPeople(
       this List list, 
       CompareOptions opt1,
       SortOrder ord) )
    
       list.Sort( (x,y) => {
         int comp = 0;
         switch (opt) {
           case CompareOptions.ByFirstName: comp = x.FirstName.CompareTo(y.FirstName);
           case CompareOptions.ByLastName: comp = x.LastName.CompareTo(y.LastName);
           case CompareOptions.BySalary: comp = x.Salary.CompareTo(y.Salary);
           default: throw new Exception();
         }
         if ( ord == SortOrder.Descending ) {
           comp = -comp;
         }
         return comp;
       });
    }
    

提交回复
热议问题