static void Main()
{
var people = new ArrayList();
people.AddRange(new ArrayList
{
new Person{ Name = "Jone",Age = },
new Person{ Name = "Tom",Age = },
new Person{ Name = "Lily",Age = },
new Person {Name = "July",Age = }
});
Console.WriteLine("↓↓↓ Old ↓↓↓");
foreach (Person person in people)
{
Console.WriteLine($"person name:{person.Name} age:{person.Age}");
}
people.Sort(); //new PersonComparer()
Console.WriteLine("↓↓↓ New ↓↓↓");
foreach (Person person in people)
{
Console.WriteLine($"person name:{person.Name} age:{person.Age}");
} Console.ReadKey();
}

IComparable 是用于类对其的CompareTo方法进行实现,比较的对象包含自身,并且集合调用默认的Sort方法 (个人理解是框架提供的默认比较方式)

   class  Person :IComparable
{
public string Name { get; set; } public int Age { get; set; }
public int CompareTo(object obj)
{
if (obj is Person person)
{
return this.Age - person.Age;
}
else
{
throw new ArgumentException("Object is not a Person");
}
}
}

IComparer  是比较两个Object,是以比较器的形式存在的,并且集合调用Sort(new XxxComparer())方法(个人理解是框架对默认比较方式的扩展吧,用以满足特定的需求)

 class PersonComparer:IComparer
{
public int Compare(object x, object y)
{
if (x is Person personX && y is Person personY)
{
if (Object.ReferenceEquals(x,y))
{
return ;
}
int result = String.Compare(personX.Name, personY.Name, StringComparison.Ordinal);
if (result == )
{
result = personX.Age - personY.Age;
} return result;
}
else
{
throw new ArgumentException("Object is not a Person");
}
}
}

最新文章

  1. 【原】tomcat 7 启动报错:java.lang.NoSuchMethodError: javax.servlet.ServletContext.getSessionCookieConfig()Ljavax/servlet/SessionCookieConfig的解决
  2. 在WPF中使用WinForm控件方法
  3. CSS实现小三角小技巧
  4. 三元运算与lambda表达式
  5. .net MVC 中枚举类型Enum 转化成 下拉列表的数据源
  6. 深入理解URL
  7. ThinkPHP项目整合UCenter(一)
  8. bootstrap的验证和确认对话框
  9. How to crack interviews ...
  10. NServiceBus-性能测试
  11. windows下 berkerly db的安装配置(修正了关键步骤)
  12. ProfessionalKnowledgeArchitecture
  13. PCB板上镀镍厚度
  14. (高级篇 Netty多协议开发和应用)第十章-Http协议开发应用(基于Netty的HttpServer和HttpClient的简单实现)
  15. [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统
  16. ( 转) Awesome Image Captioning
  17. hashContext
  18. 嵌入式 Web Server 温度检测系统
  19. day37(类加载器)
  20. 让sublime text3支持Vue语法高亮显示[转]

热门文章

  1. Python 装饰器的总结
  2. 在 Azure 虚拟机中配置 Always On 可用性组(经典)
  3. SSM框架——实现分页和搜索分页
  4. 沉淀再出发:dubbo的基本原理和应用实例
  5. Economy a Two-Edged Sword for Democrats
  6. BZOJ1016:[JSOI2008]最小生成树计数(最小生成树,DFS)
  7. Bootstrap--模仿官网写一个页面
  8. ethereumjs/merkle-patricia-tree-1-简介
  9. random模块 参生随机数
  10. Linux 嵌入式 开发环境 交叉编译安装