using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections; namespace Demo3
{
class Program
{
static void Main(string[] args)
{
//新建集合people用来存放person实例
ArrayList people = new ArrayList();
//建立4个person实例
Person person1 = new Person("Jone", 18);
Person person2 = new Person("Tom", 20);
Person person3 = new Person("Lily", 15);
Person person4 = new Person("July", 25);
//将实例添加到people集合中
people.Add(person1);
people.Add(person2);
people.Add(person3);
people.Add(person4);
//输出原来序列
Console.WriteLine("原来序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
//用实现Icomparable进行排序
people.Sort();
//用实现Icomparable的方法输出排序后的序列
Console.WriteLine("按年龄排序后的序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
//用实现Icomparer的方法进行排序
people.Sort(PersonComparer.Default);
//用实现Icomparer的方法输出排序后的序列
Console.WriteLine("按名称排序后的序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
Console.ReadKey();
}
} public class Person : IComparable
{
/// <summary>
/// 两个私有字段:
/// 人物姓名;
/// 人物年龄;
/// </summary>
private string name;
private int age; /// <summary>
/// 构造函数
/// </summary>
public Person(string myname, int myage)
{
name = myname;
age = myage;
} /// <summary>
/// 两个共有属性:
/// 分别对应两个私有字段;
/// </summary>
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
public int Age
{
set
{
age = value;
}
get
{
return age;
}
} public int CompareTo(object myobject)
{
if (myobject is Person)//用is运算符判断要比较的对象是否是Person对象
{
//如果是用as运算符进行对象转换,返回年龄比较结果(一个整数,表示两者差)
Person myperson = myobject as Person;
return this.Age - myperson.Age;
//return myperson.Age - this.Age;
}
else
{
//如果不是,抛出异常
throw new ArgumentException("Object to compare to is not a Person Object");
}
}
} public class PersonComparer : IComparer
{
//静态字段,方便使用,没有也可,调用方法会变
public static IComparer Default = new PersonComparer();
public int Compare(object myperson1, object myperson2)
{
//用is运算符判断要比较的对象是否都是Person对象
if (myperson1 is Person && myperson2 is Person)
{
//如果是,调用.Net Framework已经实现好的能比较基本类型的函数:Comparer.Default.Compare
//(要用using System.Collections;)
return Comparer.Default.Compare(((Person)myperson1).Name, ((Person)myperson2).Name);
}
else
{
//如果不是抛出异常
throw new ArgumentException("One or both objects to compare are not Person objects.");
}
}
}
}

Icomparer和Icomparable集合排序-LMLPHP

方法论:读书加上网查询相关资料,能够更好的理解知识点。

05-08 08:28