C# - Sorting using Extension Method

前端 未结 4 983
野趣味
野趣味 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:34

    To get this to work in a lambda, the expression needs to form a Comparison signature. This would take 2 "Person" instances. You could do this like:

    public static void SortPeople(
        this List lst, CompareOptions opt1,SortOrder ord)
    {
        lst.Sort((left, right) => 
                 {
                     int result;
                     // left and right are the two Person instances
                     if (opt1 == CompareOptions.Salary)
                     {
                         result = left.Salary.CompareTo(right.Salary);
                     }
                     else
                     {
                         string compStr1, compStr2;
                         if (opt1 == CompareOptions.FirstName)
                         {
                              compStr1 = left.FirstName;
                              compStr2 = right.FirstName;
                         }
                         else
                         {
                              compStr1 = left.LastName;
                              compStr2 = right.LastName;
                         }
                         result = compStr1.CompareTo(compStr2);
                     }
                     if (ord == SortOrder.Descending)
                         result *= -1;
                     return result;
                 });
    }
    

提交回复
热议问题