标签:
using System;
using System.Collections.Generic;
public class MyClass
{
public class Employee:IComparable<Employee>
{
public int EmpID;
public string YearsOfSvc = "1";
public Employee(int id)
{
EmpID = id;
}
public Employee(int id , string ys)
{
this.EmpID = id;
this.YearsOfSvc = ys;
}
public int CompareTo(Employee rhs)
{
return this.EmpID.CompareTo(rhs.EmpID);
}
public int CompareTo(Employee rhs,Employee.EmployeeComparer.ComparisonType which)
{
switch(which)
{
case Employee.EmployeeComparer.ComparisonType.EmpID:
return this.EmpID.CompareTo(rhs.EmpID);
break;
case Employee.EmployeeComparer.ComparisonType.Yrs:
return this.YearsOfSvc.CompareTo(rhs.YearsOfSvc);
break;
}
return 0;
}
public static Employee.EmployeeComparer GetComparer()
{
return new Employee.EmployeeComparer();
}
public class EmployeeComparer:IComparer<Employee>
{
private ComparisonType whichComparison;
public enum ComparisonType
{
EmpID,
Yrs
}
public int Compare(Employee lhs,Employee rhs )
{
return lhs.CompareTo(rhs,whichComparison);
}
public Employee.EmployeeComparer.ComparisonType WhichComparison
{
get{return whichComparison;}
set{whichComparison = value;}
}
}
}
public static void RunSnippet()
{
List<Employee> list = new List<Employee>();
list.Add(new Employee(1,"how"));
list.Add(new Employee(0,"are"));
list.Add(new Employee(-1,"you"));
list.Add(new Employee(4,"fine"));
list.Add(new Employee(3,"thanks"));
Employee.EmployeeComparer c = Employee.GetComparer();
c.WhichComparison = Employee.EmployeeComparer.ComparisonType.Yrs;
list.Sort(c);
for(int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i].YearsOfSvc);
}
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
标签:
原文地址:http://www.cnblogs.com/jinweijie0527/p/4952960.html