标签:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace no._1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr1 = new ArrayList() {
new Person() { Name="Shi",Age=17 },
new Person() { Name="Da",Age=21 },
new Person() { Name="Wu",Age=14 }};
Console.WriteLine("arr1 Before:");
for (int i = 0; i < arr1.Count; i++)
{
Console.WriteLine(((Person)arr1[i]).Name);
}
arr1.Sort();
Console.WriteLine("arr1 After Sort:");
for (int i = 0; i < arr1.Count; i++)
{
Console.WriteLine(((Person)arr1[i]).Name);
}
ArrayList arr2 = new ArrayList() {
new Person() { Name="K",Age=21 },
new Person() { Name="D",Age=24 },
new Person() { Name="W",Age=15 },
new Person() { Name="Z",Age=25 } };
Console.WriteLine("arr2 Before:");
for (int i = 0; i < arr2.Count; i++)
{
Console.WriteLine(((Person)arr2[i]).Name);
}
arr2.Sort(new PersonByAge());
Console.WriteLine("arr2 After Sort:");
for (int i = 0; i < arr2.Count; i++)
{
Console.WriteLine(((Person)arr2[i]).Name);
}
Console.ReadKey();
}
class PersonByAge : IComparer
{
public int Compare(object x, object y)
{
Person p1 = x as Person;
Person p2 = y as Person;
if(p1!=null && p2!=null)
{
return p1.Age - p2.Age;
}
else
{
throw new ArgumentException() { };
}
}
}
class Person : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(object obj)
{
Person p = obj as Person;
if (p == null)
{
throw new ArgumentException() { };
}
else
{
return p.Age - this.Age;
}
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/shiblog/p/4915895.html