using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Class1 { public string Name; public int Price; public Class1(string name, int price) { this.Name = name; this.Price = price; } public static bool Compare(Class1 c1,Class1 c2) { if (c1.Price > c2.Price) return true; else return false; } public override string ToString() { return Name + ":" + Price; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void CommonSort<T>(T[] sortArray,Func<T,T,bool> compareMethod)//传递T类型的数组,T类型的比较方法,返回bool类型 { bool isTrue = true; do { isTrue = 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; isTrue = true; } } } while (isTrue); } static void Main(string[] args) { Class1[] class1 = new Class1[] { new Class1("zhangsan",18), new Class1("lisi",56), new Class1("wangwu",32), new Class1("zhangsan",8), new Class1("xiongda",68), new Class1("zhaoqi",77), new Class1("xionger",40) }; CommonSort<Class1>(class1,Class1.Compare); foreach (Class1 temp in class1) { Console.WriteLine(temp.ToString()); } Console.ReadKey(); } } }