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

ASP.NET
asp.net 禁用viewstate在web.config里
asp.net 虚方法、抽象方法、接口疑问
c# 操作符?? null coalescing operator
.net 反序题目的详细解答
implicitly convert type ''int'' to ''short''的原因与解决方法
比较完整的 asp.net 学习流程
官网 Ext direct包中.NET版的问题
C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)
c# 连接字符串数据库服务器端口号 .net状态服务器端口号
ASP.NET 路径问题的解决方法
asp.net TemplateField模板中的Bind方法和Eval方法
asp.net Web.config 详细配置说明
asp.net 2个日期之间的整月数的算法
ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效
Request.RawUrl 属性的应用收
.net 读取项目AssemblyInfo.cs属性值
asp.net URL 显示乱码 解决方法
asp.net 页面之间传递参数的几种方法
asp.net 一个封装比较完整的FTP类
C# FTP,GetResponse(),远程服务器返回错误

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


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