C#基础之数组排序,对象大小比较
转: http://www.cnblogs.com/yukaizhao/archive/2011/08/19/csharp-compare.html从个小例子开始:
1
int
[] intArray =
new
int
[]{2,3,6,1,4,5};
2
Array.Sort(intArray);
3
Array.ForEach<
int
>(intArray,(i)=>Console.WriteLine(i));
这个例子定义了一个int数组,然后使用Array.Sort(arr)静态方法对此数组进行排序,最后输出排序后的数组。以上例子将毫无意外的依次输出1,2,3,4,5,6.
为什么Array的Sort方法可以正确的对int数组进行排序呢,我们自定义类可以吗?试试看,如下代码:
01
public
class
Student
02
{
03
public
int
Age {
get
;
set
;
}
04
05
public
string
Name {
get
;
set
;
}
06
07
public
int
Score {
get
;
set
;
}
08
}
09
10
11
12
static
void
Main(
string
[] args)
13
{
14
Student[] students =
new
Student[]{
15
new
Student(){Age =
10,Name="张三"
,Score=70},
16
new
Student(){Age =
12,Name="李四"
,Score=97},
17
new
Student(){Age =
11,Name="王五"
,Score=80},
18
new
Student(){Age =
9,Name="赵六"
,Score=66},
19
new
Student(){Age =
12,Name="司马"
,Score=90},
20
};
21
22
Console.WriteLine(
"--------------默认排序输出--------"
);
23
Array.Sort(students);
24
Array.ForEach<Student>(students,(s)=>Console.WriteLine(
string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,s.Name,s.Age,s.Score)));
25
26
Console.Read();
27
}
我们定义了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接口.
01
public
class
Student
:IComparable
02
{
03
public
int
Age {
get
;
set
;
}
04
05
public
string
Name {
get
;
set
;
}
06
07
public
int
Score {
get
;
set
;
}
08
09
10
/// <summary>
11
/// 实现IComparable接口,用Age做比较
12
/// </summary>
13
/// <param
name="obj">比较对象</param>
14
///
<returns>比较结果</returns>
15
public
int
CompareTo(
object
obj)
16
{
17
if
(obj
is
Student)
18
{
19
return
Age.CompareTo(((Student)obj).Age);
20
}
21
22
return
1;
23
}
24
}
在Student类中实现了IComparable接口,在CompareTo方法中比较Student的Age属性,这一次再次编译运行,程序正常的输出了按照年龄排序的Student数组。
假如说我们要对Student的Score属性进行排序该怎么办呢? Student类实现的IComparable接口只能按照一种属性排序呀。
这个是很容易实现的.net的类库开发者早为我们准备了另一个接口IComparer<T>接口用来实现比较类型T的两个实例。如下StudentScoreComparer类实现了对Student按照Score属性比较的IComparer<Student>
1
public
class
StudentScoreComparer : IComparer<Student>
2
{
3
public
int
Compare(Student x, Student y)
4
{
5
return
x.Score.CompareTo(y.Score);
6
}
7
}
现在我们可以使用下面代码对Student数组按照Score属性进行排序:
1
Console.WriteLine(
"----------按分数排序输出------------"
);
2
Array.Sort(students,
new
StudentScoreComparer());
3
Array.ForEach<Student>(students, (s) =>
Console.WriteLine(string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,
s.Name, s.Age, s.Score)));
不过一个简单的按照Score属性排序,再定义一个类是不是有点大题小作呀,有没有更好的办法呢?当然有.
.net为我们准备了比较对象大小的委托Comparison<T>我们可以使用拉姆达表达式或者匿名委托直接排序,如下代码实现:
1
Console.WriteLine(
"----------按分数排序输出----------"
);
2
Array.Sort(students, (s1, s2) =>
s1.Score.CompareTo(s2.Score));
3
Array.ForEach<Student>(students, (s) =>
Console.WriteLine(string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,
s.Name, s.Age, s.Score)));
完整代码示例如下:
01
using
System;
02
using
System.Collections.Generic;
03
using
System.Linq;
04
using
System.Text;
05
06
namespace
SortingInCSharp
07
{
08
class
Program
09
{
10
public
class
Student : IComparable
11
{
12
public
int
Age {
get
;
set
;
}
13
14
public
string
Name {
get
;
set
;
}
15
16
public
int
Score {
get
;
set
;
}
17
18
/// <summary>
19
/// 实现IComparable接口,用Age做比较
20
/// </summary>
21
/// <param
name="obj">比较对象</param>
22
///
<returns>比较结果</returns>
23
public
int
CompareTo(
object
obj)
24
{
25
if
(obj
is
Student)
26
{
27
return
Age.CompareTo(((Student)obj).Age);
28
}
29
30
return
1;
31
}
32
}
33
34
static
void
Main(
string
[] args)
35
{
36
Student[] students =
new
Student[]{
37
new
Student(){Age =
10,Name="张三"
,Score=70},
38
new
Student(){Age =
12,Name="李四"
,Score=97},
39
new
Student(){Age =
11,Name="王五"
,Score=80},
40
new
Student(){Age =
9,Name="赵六"
,Score=66},
41
new
Student(){Age =
12,Name="司马"
,Score=90},
42
};
43
44
Console.WriteLine(
"--------------默认排序输出--------"
);
45
Array.Sort(students);
46
Array.ForEach<Student>(students,
(s) =>
Console.WriteLine(string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,
s.Name, s.Age, s.Score)));
47
48
Console.WriteLine(
"----------按分数排序输出------------"
);
49
Array.Sort(students,
new
StudentScoreComparer());
50
Array.ForEach<Student>(students,
(s) =>
Console.WriteLine(string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,
s.Name, s.Age, s.Score)));
51
52
Console.WriteLine(
"----------按分数排序输出----------"
);
53
Array.Sort(students, (s1, s2) =>
s1.Score.CompareTo(s2.Score));
54
Array.ForEach<Student>(students,
(s) =>
Console.WriteLine(string
.Format(
"{0}{1,2}岁了,他的分数是{2,3}"
,
s.Name, s.Age, s.Score)));
55
56
57
Console.Read();
58
}
59
60
public
class
StudentScoreComparer : IComparer<Student>
61
{
62
public
int
Compare(Student x, Student y)
63
{
64
return
x.Score.CompareTo(y.Score);
65
}
66
}
67
}
68
}
总结:
在C#中有三个关于比较对象大小的接口,分别是IComparable、IComparable<T>和IComparer<T>。
IComparable和IComparable<T>是类本身实现的在实例之间比较大小的行为定义。IComparer<T>是定义在被比较类之外的专门比较两个T类型对象大小的行为,另外还有一个用于比较的委托定义Comparison<T>可以让我们用拉姆达表达式或者匿名委托或方法更方便的排序。
请尊重作者的劳动,转载请保留链接 玉开的技术博客