C#基础之数组排序、对象大小比较实现代码
2023-06-13 09:14:30 时间
从个小例子开始:
复制代码代码如下:
int[]intArray=newint[]{2,3,6,1,4,5};
Array.Sort(intArray);
Array.ForEach<int>(intArray,(i)=>Console.WriteLine(i));
这个例子定义了一个int数组,然后使用Array.Sort(arr)静态方法对此数组进行排序,最后输出排序后的数组。以上例子将毫无意外的依次输出1,2,3,4,5,6.
为什么Array的Sort方法可以正确的对int数组进行排序呢,我们自定义类可以吗?试试看,如下代码:
publicclassStudent
{
publicintAge{get;set;}
publicstringName{get;set;}
publicintScore{get;set;}
}
staticvoidMain(string[]args)
{
Student[]students=newStudent[]{
newStudent(){Age=10,Name="张三",Score=70},
newStudent(){Age=12,Name="李四",Score=97},
newStudent(){Age=11,Name="王五",Score=80},
newStudent(){Age=9,Name="赵六",Score=66},
newStudent(){Age=12,Name="司马",Score=90},
};
Console.WriteLine("--------------默认排序输出--------");
Array.Sort(students);
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
Console.Read();
}
我们定义了Student类然后同样对他的数组进行排序,程序正确的编译通过,但是运行出错,运行时抛出了异常:System.InvalidOperationException{"Failedtocomparetwoelementsinthearray."},这个异常的InnerException是ArgumentException{"AtleastoneobjectmustimplementIComparable."};运行时异常说明:我们要使用Array.Sort(arr)静态方法,必须得保证数组中有一个元素实现IComparable接口。既然如此我们就让Student类实现IComparable接口.
publicclassStudent:IComparable
{
publicintAge{get;set;}
publicstringName{get;set;}
publicintScore{get;set;}
///<summary>
///实现IComparable接口,用Age做比较
///</summary>
///<paramname="obj">比较对象</param>
///<returns>比较结果</returns>
publicintCompareTo(objectobj)
{
if(objisStudent)
{
returnAge.CompareTo(((Student)obj).Age);
}
return1;
}
}
在Student类中实现了IComparable接口,在CompareTo方法中比较Student的Age属性,这一次再次编译运行,程序正常的输出了按照年龄排序的Student数组。
假如说我们要对Student的Score属性进行排序该怎么办呢?Student类实现的IComparable接口只能按照一种属性排序呀。
这个是很容易实现的.net的类库开发者早为我们准备了另一个接口IComparer<T>接口用来实现比较类型T的两个实例。如下StudentScoreComparer类实现了对Student按照Score属性比较的IComparer<Student>
publicclassStudentScoreComparer:IComparer<Student>
{
publicintCompare(Studentx,Studenty)
{
returnx.Score.CompareTo(y.Score);
}
}
现在我们可以使用下面代码对Student数组按照Score属性进行排序:
Console.WriteLine("----------按分数排序输出------------");
Array.Sort(students,newStudentScoreComparer());
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
不过一个简单的按照Score属性排序,再定义一个类是不是有点大题小作呀,有没有更好的办法呢?当然有..net为我们准备了比较对象大小的委托Comparison<T>我们可以使用拉姆达表达式或者匿名委托直接排序,如下代码实现:
Console.WriteLine("----------按分数排序输出----------");
Array.Sort(students,(s1,s2)=>s1.Score.CompareTo(s2.Score));
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
完整代码示例如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceSortingInCSharp
{
classProgram
{
publicclassStudent:IComparable
{
publicintAge{get;set;}
publicstringName{get;set;}
publicintScore{get;set;}
///<summary>
///实现IComparable接口,用Age做比较
///</summary>
///<paramname="obj">比较对象</param>
///<returns>比较结果</returns>
publicintCompareTo(objectobj)
{
if(objisStudent)
{
returnAge.CompareTo(((Student)obj).Age);
}
return1;
}
}
staticvoidMain(string[]args)
{
Student[]students=newStudent[]{
newStudent(){Age=10,Name="张三",Score=70},
newStudent(){Age=12,Name="李四",Score=97},
newStudent(){Age=11,Name="王五",Score=80},
newStudent(){Age=9,Name="赵六",Score=66},
newStudent(){Age=12,Name="司马",Score=90},
};
Console.WriteLine("--------------默认排序输出--------");
Array.Sort(students);
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
Console.WriteLine("----------按分数排序输出------------");
Array.Sort(students,newStudentScoreComparer());
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
Console.WriteLine("----------按分数排序输出----------");
Array.Sort(students,(s1,s2)=>s1.Score.CompareTo(s2.Score));
Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
Console.Read();
}
publicclassStudentScoreComparer:IComparer<Student>
{
publicintCompare(Studentx,Studenty)
{
returnx.Score.CompareTo(y.Score);
}
}
}
}
总结:
在C#中有三个关于比较对象大小的接口,分别是IComparable、IComparable<T>和IComparer<T>。IComparable和IComparable<T>是类本身实现的在实例之间比较大小的行为定义。IComparer<T>是定义在被比较类之外的专门比较两个T类型对象大小的行为,另外还有一个用于比较的委托定义Comparison<T>可以让我们用拉姆达表达式或者匿名委托或方法更方便的排序。
相关文章
- 【C#基础】-Substring截取字符串的方法小结
- 【小5聊】C#基础之Response.ContentType响应内容类型[通俗易懂]
- C#网络编程(Socket编程)「建议收藏」
- 字符串转整型c#_java字符串数组转字符串
- c# 多线程并发-金三银四面试:C#.NET面试题高级篇2-多线程
- Unity脚本(C#)基础笔记
- C#命名管道通信详解编程语言
- 传智播客C#编程基础免费下载
- c#钩子学习笔记
- C#反射的一些应用
- C#基础继承和多态详解
- 带着问题读CLRviaC#(笔记二)类型基础
- C#基础延迟加载介绍与实例
- 浅析C#基础语法的使用
- C#基础:Equals()与运算符==的区别分析
- c#基础学习之封装
- c#多线程编程基础
- c#瀛?绗︿覆?肩被??涓?寮??ㄧ被??姣?杈?绀轰?
- C#实现软件监控外部程序运行状态的方法
- C#实现移除字符串末尾指定字符的方法