当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C# 数组查找与排序实现代码

ASP.NET
用ASP.NET加密Cookie数据
用ASP.NET开发Web服务的五则技巧
ASP.NET数据库缓存依赖
ASP.Net开发者常见Datagrid错误
asp.net 2.0多语言网站解决方案
在ASP.NET中值得注意的两个地方
用.net静态变量取代Application 速度更快
ASP.NET图象处理详解(1)
ASP.NET图象处理详解(2)
使用JScript.NET创建asp.net页面
ASP.NET中水晶报表的使用
数据库连接字在Web.config里的用法
浅谈在ASP.NET中数据有效性校验的方法
ASPX页Web服务调用性能优化
从 PHP 迁移到 ASP.NET
ASP.NET中编程杀死进程
ASP.NET保持用户状态的九种选择(上)
ASP.NET保持用户状态的九种选择(下)
使用更精简的代码保证ASP.NET应用程序的安全
为ASP.NET应用缓存Oracle数据

ASP.NET 中的 C# 数组查找与排序实现代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-11   浏览: 386 ::
收藏到网摘: n/a

数组查找对象的方法一种是查找对象,一种是查找值 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);