数组查找对象的方法一种是查找对象,一种是查找值
1. 查找对象
Person p1
=
new
Person(
"
http://www.my400800.cn
"
,
18
);
Person p2
=
new
Person(
"
http://www.my400800.cn
"
,
19
);
Person p3
=
new
Person(
"
http://www.my400800.cn
"
,
20
);
Person[] persons
=
...
{ p1, p2, p3 }
;
//
查找p2所在数组中的位置
Array.IndexOf
<
Person
>
(persons, p2);
2. 查找值
Person p1
=
new
Person(
"
http://www.my400800.cn
"
,
18
);
Person p2
=
new
Person(
"
http://blog.my400800.cn
"
,
19
);
Person p3
=
new
Person(
"
http://
blog.my400800.cn/400电话
"
,
20
);
Person[] persons
=
...
{ p1, p2, p3 }
;
Person p4
=
new
Person(p2.Name, p2.Age);
//
查找数组中与p4相同的元素所在的位置
Array.IndexOf
<
Person
>
(persons, p4);
但是,这种方法必需使Person重载Object的 Equals 比较方法
public
override
bool
Equals(
object
obj)
...
{
Person person
=
obj
as
Person;
if
(person
==
null
)
return
false
;
return
(
this
.name
==
person.name
&&
this
.age
==
person.age);
}
第二种按对象的值查找的方法
实现IComparabler接口
public
int
CompareTo(
object
obj)
...
{
Person person
=
obj
as
Person;
if
(person
==
null
)
throw
new
Exception(
"
The method or operation is not implemented.
"
);
//
先从年龄开始比较
int
ageResult
=
this
.age.CompareTo(person.age);
if
(ageResult
==
0
)
...
{
//
如果年龄相等在坐姓名比较
return
this
.name.CompareTo(person.name);
}
else
...
{
return
ageResult;
}
}
实现了IComparable接口后就可以使用Array.BinarySearch()进行查找了
//
得到 person 在 persons 中有相同值的下标
//
如果多个相同的值,BinarySearch将取最后
//
一个有相同值的数组下标
Array.BinarySearch
<
Person
>
(persons, person);
注:使用Array.BinarySeach必须操作一个排序好的数组
3. 排序
只要对象实现了IComparable接口,就可以使用Array中静态的方法Sort进行排序
//
必需使比较的对象实现IComparable接口
Array.Sort
<
Person
>
(persons);