IComparer 与 IComparable
2024-09-04 11:32:56
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");
}
}
}
最新文章
- 【原】tomcat 7 启动报错:java.lang.NoSuchMethodError: javax.servlet.ServletContext.getSessionCookieConfig()Ljavax/servlet/SessionCookieConfig的解决
- 在WPF中使用WinForm控件方法
- CSS实现小三角小技巧
- 三元运算与lambda表达式
- .net MVC 中枚举类型Enum 转化成 下拉列表的数据源
- 深入理解URL
- ThinkPHP项目整合UCenter(一)
- bootstrap的验证和确认对话框
- How to crack interviews ...
- NServiceBus-性能测试
- windows下 berkerly db的安装配置(修正了关键步骤)
- ProfessionalKnowledgeArchitecture
- PCB板上镀镍厚度
- (高级篇 Netty多协议开发和应用)第十章-Http协议开发应用(基于Netty的HttpServer和HttpClient的简单实现)
- [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统
- ( 转) Awesome Image Captioning
- hashContext
- 嵌入式 Web Server 温度检测系统
- day37(类加载器)
- 让sublime text3支持Vue语法高亮显示[转]
热门文章
- Python 装饰器的总结
- 在 Azure 虚拟机中配置 Always On 可用性组(经典)
- SSM框架——实现分页和搜索分页
- 沉淀再出发:dubbo的基本原理和应用实例
- Economy a Two-Edged Sword for Democrats
- BZOJ1016:[JSOI2008]最小生成树计数(最小生成树,DFS)
- Bootstrap--模仿官网写一个页面
- ethereumjs/merkle-patricia-tree-1-简介
- random模块 参生随机数
- Linux 嵌入式 开发环境 交叉编译安装