ArrayList排序问题
2018-01-20 本文已影响9人
蓝色Hippie
ArrayList集合,包含默认的方法Sort(),这个方法使用时可以不带参数,此时使用默认的比较方式,也可以给它传送IComparer接口。
给ArrayList填充了简单类型时,例如整数或者字符串,就会进行默认的比较。对于自己的类,必须在类定义中实现IComparable,或创建一个支持IComparer的类,来进行比较。
1.Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Person:IComparable
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
}
else {
throw new ArgumentException("Object to compare to is not a Person object ");
}
}
}
}
2.PsersonCompareName.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
public class PsersonCompareName:IComparer
{
public static IComparer Default = new PsersonCompareName();
public int Compare(object x, object y)
{
if (x is Person && y is Person)
{
return Comparer.Default.Compare(((Person)x).Name, ((Person)y).Name);
}
else {
throw new ArgumentException("error");
}
}
}
}
3.调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("R",30));
list.Add(new Person("D", 25));
list.Add(new Person("M", 27));
list.Add(new Person("B", 44));
Console.WriteLine("Unsorted people:");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine((list[i] as Person).Name + " " + (list[i] as Person).Age);
}
Console.WriteLine("default sort");
list.Sort();
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine((list[i] as Person).Name + " " + (list[i] as Person).Age);
}
Console.WriteLine("not default sort");
list.Sort(PsersonCompareName.Default);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine((list[i] as Person).Name + " " + (list[i] as Person).Age);
}
}
}
}
