通过委托自定义排序规则

话不多说直接看代码

  public static void Sort<T>(IList<T> sortArr, Func<T, T, bool> compare)
        {
            bool flag = true;
            do
            {
                flag = false;
                for (int i = 0; i < sortArr.Count - 1; i++)
                {
                    if (compare(sortArr[i], sortArr[i + 1]))
                    {
                        T temp = sortArr[i];
                        sortArr[i] = sortArr[i + 1];
                        sortArr[i + 1] = temp;
                        flag = true;
                    }
                }
            } while (flag);
        }
 public class Emp
    {
        public string Name { get; set; }
        public decimal Salary { get; set; }
        public Emp(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }
        public override string ToString() => $"Name:{Name},Salary:{Salary:c}";
        public static bool CompareSalary(Emp emp1, Emp emp2) => emp1.Salary > emp2.Salary;
    }
//调用方式
  Emp[] employees = { new Emp("Bugs", 20000), new Emp("Eugs", 10000), new Emp("Dugs",         
  25000), new Emp("Wugs", 10000000.38m) };
            BubbleSorter.Sort(employees, Emp.CompareSalary);
            foreach (var item in employees)
            {
                Console.WriteLine(item);
            }

猜你喜欢

转载自blog.csdn.net/qq_31975127/article/details/85244053
今日推荐