从一开始的继承Icomparer接口到现在的扩展方法和lambda表达式:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace In_Depth_Demo { class Program { static void Main(string[] args) { List<Product> list = new List<Product>() { new Product() { name = "a", price = 1 }, new Product() { name = "1", price = 2 }, new Product() { name = "2", price = 3 }, new Product() { name = "1", price = 4 } }; //扩展方法 foreach (Product obj in list.OrderByDescending(p => p.price)) //倒叙排列 { Console.WriteLine(obj.price); } //lambda //list.Sort((x, y) => x.price.CompareTo(y.price)); //根据价格排序 //foreach (Product obj in list) //{ // Console.WriteLine(obj.price); //} //委托 //list.Sort(delegate (Product x, Product y) { return x.name.CompareTo(y.name); }); //foreach (Product obj in list) //{ // Console.WriteLine(obj.name); //} //老版本写法 //Product p1 = new Product() { name = "a", price = 1 }; //Product p2 = new Product() { name = "1", price = 2 }; //Product p3 = new Product() { name = "3", price = 3 }; //Product p4 = new Product() { name = "2", price = 4 }; //ArrayList arrayList = new ArrayList(); //arrayList.Add(p1); //arrayList.Add(p2); //arrayList.Add(p3); //arrayList.Add(p4); //arrayList.Sort(new ProductNameComparer()); //foreach (Product obj in arrayList) //{ // Console.WriteLine(obj.name); //} Console.ReadLine(); } } class ProductNameComparer : IComparer { public int Compare(object x, object y) { Product first = (Product)x; Product second = (Product)y; return second.name.CompareTo(first.name); //反过来正序 } } public class Product { public int price; public string name; } }