1. 定义Car类,练习Lambda表达式拍序
(1)Car类中包含两个字段:name和price;
(2)Car类中包含相应的属性、构造函数及ToString方法;
(3)在Main方法中定义Car数组,并实例化该数组;
(4)在Main方法中,按姓名排序输出Car数组所有元素。
(5)在Main方法中,先按姓名后按价格排序输出Car数组所有元素。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Myproject
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Car[] cars = new Car[4];
14 
15             cars[0] = new Car("B", 80);
16             cars[1] = new Car("A", 90);
17             cars[2] = new Car("C", 70);
18             cars[3] = new Car("b", 80);
19 
20             List<Car> List_Car = new List<Car> { cars[0], cars[1], cars[2] ,cars[3] };
21             Console.WriteLine( "待排序序列 :");
22             foreach (var item in List_Car )
23             {
24                 Console.WriteLine(item);
25             }
26 
27             List_Car.Sort((u, v) =>
28             {
29                int t = u.Price - v.Price;
30                if (t == 0)
31                {
32                    return u.Name.CompareTo(v.Name);
33                }
34                else
35                {
36                    return -t;
37                }
38             });
39 
40             Console.WriteLine("已排序序列 :");
41             foreach (var item in List_Car)
42             {
43                 Console.WriteLine(item);
44             }
45 
46         }
47     }
48     class Car
49     {
50         string name;
51         int price;
52 
53         public string Name { get { return name; } set { name = value; } }
54         public int Price { get { return price; } set { price = value; } }
55 
56         public Car (string name ,int price)
57         {
58             this.name = name;
59             this.price = price; 
60         }
61         public Car() : this("", 0) { }
62 
63         public override string ToString()
64         {
65             return string.Format("{0} : {1}",name ,price );
66         }
67 
68     }
69 }
Lambda表达式排序

相关文章:

  • 2021-07-06
  • 2022-12-23
  • 2021-12-03
  • 2021-11-13
  • 2022-01-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2022-01-19
相关资源
相似解决方案