Not much to say, the program is very simple, is the collection of data to sort, but the use of the knowledge point is still more, Daniel do not spray, I would like to dedicate to beginners! Go directly to the program!
namespacedemo{/// <summary> ///Demo: Sort elements using different sorting methods/// </summary> classProgram {Private Static voidMain (string[] args) {ArrayList ArrayList=product.getarraylist (); List<Product> list =product.getlist (); //1. Sorting using functions that inherit the IComparer interfaceArrayList.Sort (NewProductcompare ()); foreach(Product productincharrayList) {Console.WriteLine (product. ToString ()); } Console.WriteLine ("---------------------------"); //2. Sorting using functions that inherit the Icomparer<t> interfaceList. Sort (NewProductcomparet ()); foreach(Product productinchlist) {Console.WriteLine (product. ToString ()); } Console.WriteLine ("---------------------------"); //3. Use the delegate to sortList. Sort (Delegate(product x, product y) {returnX.price.compareto (Y.price); }); foreach(Product productinchlist) {Console.WriteLine (product. ToString ()); } //4, using lambda expression to sort;List. Sort ((x, y) = =X.price.compareto (Y.price)); foreach(Product productinchlist) {Console.WriteLine (product. ToString ()); } //5. Use the extension method to sort foreach(Product productinchList. (p=>P.price)) {Console.WriteLine (product. ToString ()); } console.readkey (); } } Public classProduct { Public stringName {Get;Set; } Public decimalPrice {Get;Set; } Public StaticArrayList getarraylist () {return NewArrayList () {NewProduct {Name ="WindowsPhone", Price =10m},NewProduct {Name ="Apple", Price =20m},NewProduct {Name ="Android", Price =5m}}; } Public StaticList<product>GetList () {return NewList<product>() { NewProduct {Name ="WindowsPhone", Price =10m},NewProduct {Name ="Apple", Price =20m},NewProduct {Name ="Android", Price =5m}}; } Public Override stringToString () {returnString.Format ("{0}--{1}", Name, Price); } } /// <summary> ///to sort ArrayList using IComparer///display implements the Compare interface, a collection of common ArrayList types to invoke/// </summary> Public classProductcompare:icomparer { Public intCompare (ObjectXObjecty) {Product First= X asProduct; Product Second= y asProduct; if(First! =NULL&& Second! =NULL) { returnFirst.Price.CompareTo (second. Price); } Else { return-1; } } } /// <summary> ///using IComparer<Product>to sort///Explicit implementation of the Compare interface, common list<T>a collection of types to invoke/// </summary> Public classProductcomparet:icomparer<product> { Public intCompare (product x, product y) {product First= X asProduct; Product Second= y asProduct; if(First! =NULL&& Second! =NULL) { returnFirst.Price.CompareTo (second. Price); } Else { return-1; } } }}
Demonstrate a variety of common collection sorting methods in C # by writing a demo