多條資料按照某條資料中某個共有屬性排序(氣泡排序)
阿新 • • 發佈:2018-11-08
多條資料按照某條資料中某個共有屬性排序(氣泡排序)
注意:此例是根據學生成績由高到低排序,僅供自己專案中提供思路,勿擾。
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);
}
}
}
執行結果: