Write a Demo to demonstrate multiple common set sorting methods in C,
Not to mention, the procedure is very simple, that is, to sort the data in the set, but there are still a lot of knowledge points used. Don't spray it, I would like to dedicate it to beginners! Go directly to the program!
Namespace Demo {// <summary> // Demo: sort elements using different sorting methods // </summary> class Program {private static void Main (string [] args) {ArrayList arrayList = Product. getArrayList (); List <Product> list = Product. getList (); // 1. Use the function that inherits the IComparer interface to sort arrayList. sort (new ProductCompare (); foreach (Product product in arrayList) {Console. writeLine (product. toString ();} Console. writeLine ("-------------------- ------- "); // 2. Use the function that inherits the IComparer <T> interface to sort the list. sort (new ProductCompareT (); foreach (Product product in list) {Console. writeLine (product. toString ();} Console. writeLine ("---------------------------"); // 3. Sort the list by delegation. sort (delegate (Product x, Product y) {return x. price. compareTo (y. price) ;}); foreach (Product product in list) {Console. writeLine (product. toString ();} // 4. Use a Lambda expression for sorting. li St. sort (x, y) => x. price. compareTo (y. price); foreach (Product product in list) {Console. writeLine (product. toString ();} // 5. Use the extended method to sort foreach (Product product in list. orderBy (p => p. price) {Console. writeLine (product. toString ();} Console. readKey () ;}} public class Product {public string Name {get; set;} public decimal Price {get; set;} public static ArrayList GetArrayList () {return n Ew ArrayList () {new Product {Name = "WindowsPhone", Price = 10 m}, new Product {Name = "Apple", Price = 20 m }, new Product {Name = "Android", Price = 5 m };} public static List <Product> GetList () {return new List <Product> () {new Product {Name = "WindowsPhone", Price = 10 m}, new Product {Name = "Apple", Price = 20 m}, new Product {Name = "Android ", price = 5 m }};} public override string ToString () {Return String. format ("{0} -- {1}", Name, Price );}} /// <summary> /// use IComparer to sort the ArrayList /// display to implement the Compare interface, call a set of commonly used ArrayList types // </summary> public class ProductCompare: IComparer {public int Compare (object x, object y) {Product first = x as Product; product second = y as Product; if (first! = Null & second! = Null) {return first. price. compareTo (second. price);} else {return-1 ;}}/// <summary >/// use IComparer <Product> for sorting // explicitly implement the Compare interface, call the List <T> type set in common use // </summary> public class ProductCompareT: IComparer <Product> {public int Compare (Product x, Product y) {Product first = x as Product; Product second = y as Product; if (first! = Null & second! = Null) {return first. Price. CompareTo (second. Price) ;}else {return-1 ;}}}}