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

ASP.NET
Script:WINDOWS Script 枚举运行中进程
使用Flex结合Webservice完成域名查询
VSTS Team System 总算装好了。
用于部署数据库的 数据库初始化工具 xzSQLDeploy Tools V1.0 (for SQLServer) f...
一个将阿拉伯数字转换成中文大写的最简单算法
SCRIPT:使用Windows Script 关闭和打开指定程序
Script:使用WINDOWS脚本访问WEB SERVICES
asp.net连接Access数据库
VB中IIS Application发布可能出现的问题
VB打包后的安装问题
Nhibernate的数据分页技术(续)
使用API函数复制文件,可显示进度。
VB打包技巧
VB.NET实现DirectSound9 (9) 实现示波器
VB.NET 实现DirectSound9 (10) 均衡器
[水晶报表部署系列之一]轻松搞定水晶报表9.2打包
DataGrid 中双向排序的一种办法
利用System.EventHandler来实现两个窗体间的事件调用
多线程应用程序中调用窗体的一点心得
Smart Client之旅一:用B/S方式运行Exe应用程序

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-11   浏览: 357 ::
收藏到网摘: 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);