c# ArrayList 的排序问题!
来源:互联网 发布:2016年淘宝99大促时间 编辑:程序博客网 时间:2024/06/06 08:17
c# ArrayList 的排序问题!
c# ArrayList 的排序问题!
我看见网上有人用IComparer接口实现ArrayLIst 的排序问题 ,于是自己写了个小例子,编译已经通过,和大家一块分享。有不足之处,望不吝指正。
1、建一个结构雇员的结构
private struct Eployee{
public string name;
public int age;
public string sex;
}
2、新建3个"雇员"
Eployee ep1=new Eployee();
ep1.name="小张";
ep1.age=21;
ep1.sex="男";
Eployee ep2=new Eployee();
ep2.name="老李";
ep2.age=43;
ep2.sex="男";
Eployee ep3=new Eployee();
ep3.name="施施";
ep3.age=18;
ep3.sex="男";
3、将3个"雇员" 加入"雇员列表";
ArrayList EmployeeList=newArrayList();
EmployeeList.Add(ep1);
EmployeeList.Add(ep2);
EmployeeList.Add(ep3);
好了一切准备就绪,现在希望EmployeeList中得"雇员"是按年龄排序的。
ArrayList 提供了我们现成的排序方法Sort();
它有三个重载,不管使用哪一个,至少要你提供一个Comparer:IComparer;来告诉Sort方法 你对"雇员"们的排序依据。
这个Comparer必须实现接口:System.Collections.IComparer ,该接口只有一个成员函数需要你去实现。
描述如下:
[C#]
int Compare(
object x,
object y
);
[JScript]
function Compare(
x : Object,
y : Object
) : int;
知道了这些那我们来实现一个吧
private class myEmployeeCompare:System.Collections.IComparer {
public int Compare(object x,object y){
return ((Eployee)x).age-((Eployee)y).age;
}
}
因为我们比较的是“雇员”的age,所以我们可以放心的写实现语句
return ((Eployee)x).age-((Eployee)y).age;
myEmployeeCompare EmployeeCompare=new myEmployeeCompare();
ok现在我们可以对"雇员"们按年龄排序了
EmployeeList.Sort(EmployeeCompare);
源码:
using System;
using System.Collections;
class ArrayListT{
private struct eployee
{
public string name;
public int age;
public string sex;
}
ArrayListT(){}
class eployeeCompare: System.Collections.IComparer
{
public int Compare(object x,object y)
{
return ((eployee)x).age - ((eployee)y).age;
}
}
public static void Main()
{
eployee ep1 = new eployee();
ep1.name = "小张";
ep1.age = 21;
ep1.sex = "女";
eployee ep2 = new eployee();
ep2.name = "小李";
ep2.age = 20;
ep2.sex = "女";
eployee ep3 = new eployee();
ep3.name = "小王";
ep3.age = 26;
ep3.sex = "女";
ArrayList list = new ArrayList();
list.Add(ep1);
list.Add(ep2);
list.Add(ep3);
eployeeCompare eployee = new eployeeCompare();
list.Sort(eployee);
foreach (eployee ep in list)
{
Console.WriteLine("the eployee's name is :{0} age is{1}",ep.name,ep.age);
}
Console.ReadLine();
}
}
- c# ArrayList 的排序问题!
- c# Arraylist的重复问题
- c# ArrayList排序
- c# ArrayList冒泡排序
- Array和ArrayList的自定义排序问题
- ArrayList 和LinkedList的排序问题
- ArrayList等常见集合的排序问题
- ArrayList 的 IComparer排序
- ArrayList的简单排序
- java ArrayList的排序
- java ArrayList的排序
- ArrayList的排序
- Arraylist的对象排序
- ArrayList中的数据排序问题
- ArrayList集合数据排序问题
- 认识 C# 的 ArrayList
- C# ArrayList的使用
- C# ArrayList的用法
- 远程桌面通过RDP文件进行自动登录
- Eclipse中ICTCLAS 2011 的java调用
- 高效屏幕监控
- 我们都是好孩子——石景山游乐园游记
- poj 1459 Power Network sap + gap
- c# ArrayList 的排序问题!
- pipe
- Ubuntu下安装opencv
- 韩顺平笔记__Java网络编程 实战原理
- matlab矩阵及其基本运算—特征值分解和奇异值分解
- 基于ip的手机地理定位
- 在 System Update Server 上检测到您系统的程序包目录错误。请联系 Support Center
- 获得ip地理信息的几种方法【最全】
- 理解 pkg-config 工具