sort();用法 可能考http://zhidao.baidu.com/link?url=z3O21xR9EfQ3L48BkFuy_WdnLruvZ6PLhmU3aPVfFNOpl8xNRy6u_EdoHvVHa5yVGCoEXaRi3glcRS9M5jG20a

 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Text.RegularExpressions;
 7 using System.Threading.Tasks;
 8 
 9 namespace Text
10 {
11    
12     public class Person
13     {
14         public string Name { get; set; }
15         public int Age { get; set; }
16 
17     }
18     public class PersonComparer : IComparer
19     {
20         public PersonComparer() { }
21         #region IComparer 成员
22         public int Compare(object x, object y)
23         {
24             Person p1 = x as Person;
25             Person p2 = y as Person;
26             if (p1 == null || p2 == null)
27             {
28                 throw new ArgumentException("Person为空");
29             }
30 
31             return p1.Name.CompareTo(p2.Name);
32         }
33         #endregion
34     }
35 
36     class Program
37     {
38         static void Main(string[] args)
39         {
40             List<Person> persons = new List<Person>() {
41             new Person(){Name="71.afdfd"},
42               new Person(){Name="8.afdfd"},
43                 new Person(){Name="1.afdfd"},
44                   new Person(){Name="43.afdfd"},
45                     //new Person(){Name="242.afdfd"},
46                     //  new Person(){Name="978.afdfd"},
47                     //    new Person(){Name="143.afdfd"},
48                     //      new Person(){Name="6464.afdfd"},
49                     //        new Person(){Name="245.afdfd"},
50                     //          new Person(){Name="3533.afdfd"},
51             
52             
53             };
 //方法1 使用Comparison<T>委托。下面代码使用的是lamda表达是。也可以使用匿名委托之类的,效果是一样(冒泡排序泡排序法)
54             persons.Sort((left, right) => {
55 
56 
57                 var d = Regex.Match(left.Name, @"^\d{1,}").ToString();
58                 int leftOrder = Convert.ToInt16(Regex.Match(left.Name, @"^\d{1,}").ToString());
59                 int rightOrder = Convert.ToInt16(Regex.Match(right.Name, @"^\d{1,}").ToString());
60                 Console.WriteLine(leftOrder + "====" + rightOrder + "====" + (leftOrder > rightOrder));
61                 if (leftOrder > rightOrder)
62                 {
63                     return 1;
64                 }
65                 else if (leftOrder < rightOrder)
66                 {
67                     return -1;
68                 }
69                 return 0;
70             });
71 
72             foreach (var item in persons)
73             {
74                 Console.WriteLine(item.Name);
75             }
76         }
77     }
78 }

posted on 2015-12-25 22:14  高达  阅读(534)  评论(0)    收藏  举报

导航