实现IComparer
现IComparer ,这样就可以在数组中或其它集合中自定义排序了,要实现其中的方法:
public int Compare(object x, object y)
using System;
using System.Collections;//注意using Collections
using System.Collections.Generic;
using System.Text;
namespace ZyyLove2008
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
Random random = new Random();
for (int i = 1; i < 10; i++)
{
int index = random.Next(1, 10);
Person person = new Person("zhang" + index.ToString(), index);
list.Add(person);
}
foreach (Person personTmp in list)
{
Console.WriteLine(personTmp.Name + "\t" + personTmp.Age.ToString());
}
list.Sort(new PersonComparer());
Console.WriteLine("\r\nAfter sorting\r\n");
foreach (Person personTmp in list)
{
Console.WriteLine(personTmp.Name + "\t" + personTmp.Age.ToString());
}
Console.Read();
}
}
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private int _age;
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public Person(string name, int age)
{
this._name = name;
this._age = age;
}
}
public class PersonComparer : IComparer
{
#region IComparer Members
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than,
/// equal to, or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns></returns>
public int Compare(object x, object y)
{
Person personX = x as Person;
if (personX == null)
{
throw new ArgumentException("x value is not a type of Person", "x");
}
Person personY = y as Person;
if (personY == null)
{
throw new ArgumentException("y value is not a type of Person", "y");
}
return personX.Age.CompareTo(personY.Age);
}
#endregion
}
}