class Program
{
static void Main(string[] args)
{
List<Students> objList = new List<Students>();
Students stu1 = new Students { Name = "Mick", Age = 20 };
Students stu2 = new Students { Name = "Jack", Age = 30 };
objList.Add(stu1);
objList.Add(stu2);
Console.WriteLine(stu1.Age.CompareTo(stu2.Age));
Console.WriteLine(stu1.Name.CompareTo(stu2.Name));
objList.Sort();
objList.Sort(new AgeAsc());//年龄升序
objList.Sort(new AgeDesc());//年龄降序
objList.Sort(new NameAsc());//年龄升序
objList.Sort(new NameDese());//年龄降序
foreach (var item in objList)
{
Console.WriteLine(item.Name + "-" + item.Age);
}
Console.ReadKey();
}
}
public class Students : IComparable<Students>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Students other)
{
return other.Name.CompareTo(this.Name);
}
}
public class AgeDesc :IComparer<Students>
{
public int Compare(Students x, Students y)
{
return y.Age - x.Age;
}
}
public class AgeAsc : IComparer<Students>
{
public int Compare(Students x, Students y)
{
return x.Age.CompareTo(y.Age);
}
}
public class NameDese : IComparer<Students>
{
public int Compare(Students x, Students y)
{
return y.Name.CompareTo(x.Name);
}
}
public class NameAsc : IComparer<Students>
{
public int Compare(Students x, Students y)
{
return x.Name.CompareTo(y.Name);
}
}