深入理解 c# 第一章 使用lambda表达式 对 List <Product> 进行排序

class ListSortWithLambdaExpression
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            products.Sort(
                (first, second) => first.Name.CompareTo(second.Name)
            );
            foreach (Product product in products)
            {
                Console.WriteLine(product);
            }
        }
    }
        public static List<Product> GetSampleProducts()
        {
            return new List<Product>
            {
                new Product { Name="West Side Story", Price = 9.99m },
                new Product { Name="Assassins", Price=14.99m },
                new Product { Name="Frogs", Price=13.99m },
                new Product { Name="Sweeney Todd", Price=10.99m}
            };
        }

输入  

"West Side Story", 9.99m

"Assassins", 14.99m

"Frogs", 13.99m

"Sweeney Todd", 10.99m

 输出

Assassins: 14.99
Frogs: 13.99
Sweeney Todd: 10.99
West Side Story: 9.99


用了lambda表达式,仍然会创建Camparison<Product>委托,不用delegate关键字引入委托,

设置不用指定参数类型



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页