您的位置:首页 > 其它

集合内的简单排序

2014-08-22 13:11 351 查看
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Csharp
{
class Program
{
class Person:IComparable
{
public int Age;
public int IQ;
public string Name;
public Person(string name, int age)
{
Name = name;
Age = age;
}
//implement IComparable
public int CompareTo(object obj)
{
if (obj is Person) {
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
}
else
throw new ArgumentException(
"The things we compare is not two person");
}
}

class CompareByName:IComparer
{
//implement IComparer
public static IComparer Default = new CompareByName();
public int Compare(object person1, object person2)
{
if (person1 is Person && person2 is Person)
return Comparer.Default.Compare(
((Person)person1).Name, ((Person)person2).Name);
else
throw new ArgumentException(
"There is something not Person");
}
}

static void Main(string[] args)
{
ArrayList persons = new ArrayList();
persons.Add(new Person("Ian", 21));
persons.Add(new Person("Rose", 18));
persons.Add(new Person("Briney", 23));
persons.Sort();                             //Sort by Age
foreach (Person person in persons)
Console.WriteLine("{0}", person.Name);
persons.Sort(CompareByName.Default);        //Sort by Name
foreach (Person person in persons)
Console.WriteLine("{0}", person.Name);
Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: