c# list排序的实现方式

实体类实现IComparable接口,而且必须实现CompareTo方法

实体类定义如下:

复制代码
 1 class Info:IComparable
 2     {
 3         public int Id { get; set; }
 4         public string Name { get; set; }
 5 
 6         public int CompareTo(object obj) {
 7             int result;
 8             try
 9             {
10                 Info info = obj as Info;
11                 if (this.Id > info.Id)
12                 {
13                     result = 0;
14                 }
15                 else
16                     result = 1;
17                 return result;
18             }
19             catch (Exception ex) { throw new Exception(ex.Message); }
20         }
21     }
复制代码
 
 

调用方式如下,只需要用sort方法就能实现对list进行排序。

复制代码
 1 private static void ReadAccordingCompare() {
 2             List<Info> infoList = new List<Info>();
 3             infoList.Add(
 4                 new Info() { Id = 1, Name = "abc" });
 5             infoList.Add(new Info() { Id = 3, Name = "rose" });
 6             infoList.Add(new Info() { Id = 2, Name = "woft" });
 7                infoList.Sort();
 8             foreach (var item in infoList)
 9             {
10                 Console.WriteLine(item.Id + ":" + item.Name); 
11             }
12         }
复制代码
原文地址:https://www.cnblogs.com/haofaner/p/3423153.html