using System; using System.Collections.Generic; namespace ConsoleApplication1 { class Product { public string Name { get; private set; } public decimal Price { get; private set; } public Product(string name, decimal price) { Name = name; Price = price; } public Product() { } public static List<Product> GetSampleProducts() { return new List<Product> { new Product {Name="West Side Story",Price=9.09m} , new Product {Name= "Assassins", Price=14.99m }, new Product {Name = "Progs",Price= 19.99m }, new Product {Name= "Sweeney Todd",Price = 10.99m } }; } public override string ToString() { return string.Format("{0}:{1}", Name, Price); } } class ProductPriceComparer : IComparer<Product> { public int Compare(Product x, Product y) { return x.Price.CompareTo(y.Price); } } class Program { static void Main(string[] args) { List<Product> p = Product.GetSampleProducts(); p.Sort(new ProductPriceComparer()); foreach (Product item in p) { Console.WriteLine(item.Price); } Console.ReadKey(); } } }
输出结果:
时间: 2024-10-09 09:34:07