自定义类排序
直接上代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace 自定义类排序
{
//可以让类继承
class Person:IComparable {
public string Name { get; set; }
public bool Sex { get; set; }
public int Age { get; set; }
public Person(string name,bool sex,int age) {
Name = name;
Sex = sex;
Age = age;
}
//实现IComparable
public int CompareTo(object obj) {
Person p = obj as Person;
//逻辑
int iReturn = this.Name.CompareTo(p.Name);
if (iReturn == 0) {
iReturn= this.Age.CompareTo(p.Age);
}
return iReturn;
}
}
//比较排序
class PersonSort : IComparer<Person>
{
#region IComparer<Person> 成员
public int Compare(Person p1, Person p)
{
int iReturn = p1.Name.CompareTo(p.Name);
if (iReturn == 0)
{
iReturn = p1.Age.CompareTo(p.Age);
}
return iReturn;
}
#endregion
}
class Program
{
static void Main(string[] args)
{
List<Person> listP = new List<Person>();
Person p1 = new Person("hanyuxing1", true, 25);
listP.Add(p1);
p1 = new Person("1hanyuxing", true, 25);
listP.Add(p1);
p1= new Person("2hanyuxing", true, 25);
listP.Add(p1);
p1= new Person("jhanyuxing1", false, 25);
listP.Add(p1);
p1= new Person("1hanyuxing1", true, 25);
listP.Add(p1);
p1= new Person("3hanyuxing", true, 25);
listP.Add(p1);
p1= new Person("1hanyuxing", true, 25);
listP.Add(p1);
p1= new Person("uhanyuxing", false, 25);
listP.Add(p1);
//listP.Sort();
listP.Sort(new PersonSort());
foreach (var item in listP)
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
//根据名字排序 如果名字相同按 年龄
}
}
}
一种是类实现接口ICompareable 另一种是 IComparer<Person>实现比较的接口 关键词 :Compare