欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#基础之数组排序、对象大小比较实现代码

程序员文章站 2023-11-30 08:17:22
从个小例子开始: 复制代码 代码如下: int[] intarray = new int[]{2,3,6,1,4,5}; array.sort(intarray); arr...
从个小例子开始:
复制代码 代码如下:

int[] intarray = new int[]{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数组进行排序呢,我们自定义类可以吗?试试看,如下代码:
复制代码 代码如下:

public class student
{
public int age { get; set; }
public string name { get; set; }
public int score { get; set; }
}
static void main(string[] args)
{
student[] students = new student[]{
new student(){age = 10,name="张三",score=70},
new student(){age = 12,name="李四",score=97},
new student(){age = 11,name="王五",score=80},
new student(){age = 9,name="赵六",score=66},
new student(){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{"failed to compare two elements in the array."},这个异常的innerexception是argumentexception{"at least one object must implement icomparable."};运行时异常说明:我们要使用array.sort(arr)静态方法,必须得保证数组中有一个元素实现icomparable接口。既然如此我们就让student类实现icomparable接口.
复制代码 代码如下:

public class student :icomparable
{
public int age { get; set; }
public string name { get; set; }
public int score { get; set; }
/// <summary>
/// 实现icomparable接口,用age做比较
/// </summary>
/// <param name="obj">比较对象</param>
/// <returns>比较结果</returns>
public int compareto(object obj)
{
if (obj is student)
{
return age.compareto(((student)obj).age);
}
return 1;
}
}

在student类中实现了icomparable接口,在compareto方法中比较student的age属性,这一次再次编译运行,程序正常的输出了按照年龄排序的student数组。
假如说我们要对student的score属性进行排序该怎么办呢? student类实现的icomparable接口只能按照一种属性排序呀。
这个是很容易实现的.net的类库开发者早为我们准备了另一个接口icomparer<t>接口用来实现比较类型t的两个实例。如下studentscorecomparer类实现了对student按照score属性比较的icomparer<student>
复制代码 代码如下:

public class studentscorecomparer : icomparer<student>
{
public int compare(student x, student y)
{
return x.score.compareto(y.score);
}
}

现在我们可以使用下面代码对student数组按照score属性进行排序:
复制代码 代码如下:

console.writeline("----------按分数排序输出------------");
array.sort(students, new studentscorecomparer());
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)));

完整代码示例如下:
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace sortingincsharp
{
class program
{
public class student : icomparable
{
public int age { get; set; }
public string name { get; set; }
public int score { get; set; }
/// <summary>
/// 实现icomparable接口,用age做比较
/// </summary>
/// <param name="obj">比较对象</param>
/// <returns>比较结果</returns>
public int compareto(object obj)
{
if (obj is student)
{
return age.compareto(((student)obj).age);
}
return 1;
}
}
static void main(string[] args)
{
student[] students = new student[]{
new student(){age = 10,name="张三",score=70},
new student(){age = 12,name="李四",score=97},
new student(){age = 11,name="王五",score=80},
new student(){age = 9,name="赵六",score=66},
new student(){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, new studentscorecomparer());
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();
}
public class studentscorecomparer : icomparer<student>
{
public int compare(student x, student y)
{
return x.score.compareto(y.score);
}
}
}
}

总结:
在c#中有三个关于比较对象大小的接口,分别是icomparable、icomparable<t>和icomparer<t>。 icomparable和icomparable<t>是类本身实现的在实例之间比较大小的行为定义。icomparer<t>是定义在被比较类之外的专门比较两个t类型对象大小的行为,另外还有一个用于比较的委托定义comparison<t>可以让我们用拉姆达表达式或者匿名委托或方法更方便的排序。