多条数据按照某条数据中某个共有属性排序(冒泡排序)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CSDN_Evan/article/details/52996988

多条数据按照某条数据中某个共有属性排序(冒泡排序)

注意:此例是根据学生成绩由高到低排序,仅供自己项目中提供思路,勿扰。
1、新建一个项目,在项目中添加一个Students类,用于存储学生的基本信息。
Students 类:

    class Students
    {
        public string Name { get; private set; }    //姓名
        public string Sex { get; private set; }      //性别 
        public double Score { get; private set; }   //成绩

        public Students(string name, string sex, double score)
        {
            this.Name = name;
            this.Sex = sex;
            this.Score = score;
        }

        //比较学生1和学生2谁的成绩高,如果学生2的成绩高返回true,否则返回false
        public static bool Compare(Students stud1, Students stud2)
        {
            if (stud1.Score < stud2.Score)
            {
                return true;
            }
            return false;
        }

        //用于屏幕输出
        public override string ToString()
        {
            return "姓名:" + Name + "   性别:" + Sex + "   成绩:" + Score;
        }
    }

主类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 班级成绩排序
{
    class Program
    {
        static void Main(string[] args)
        {
            Students[] students = new Students[]
            {
                new Students("张三", "男", 89),
                new Students("李四", "女", 56),
                new Students("王薇", "女", 45),
                new Students("王慧", "女", 96), 
            };
            CommonSort<Students>(students, Students.Compare);
            foreach (Students s in students)
            {
                Console.WriteLine(s.ToString());
            }
            Console.ReadKey();
        }

        static void CommonSort<T>(T[] sortArray, Func<T, T, bool> CompareMethod)
        {
            bool swaped = true;
            do
            {
                swaped = false;
                for (int i = 0; i < sortArray.Length - 1; i++)
                {
                    if (CompareMethod(sortArray[i],sortArray[i + 1]))
                    {
                        T temp = sortArray[i];
                        sortArray[i] = sortArray[i + 1];
                        sortArray[i + 1] = temp;
                        swaped = true;
                    }
                }
            } while (swaped);
        }
    }
}

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/CSDN_Evan/article/details/52996988