您的位置:首页 > 其它

比较和排序:IComparable和IComparer

2016-08-02 10:11 393 查看
创建实体类,如Person,默认按照年龄进行排序,则需要为实体类实现IComparable接口。

class Person : IComparable
{
public string Name { get; set; }

public int Age { get; set; }

public override string ToString()
{
return string.Format("Name : {0} ; Age : {1} .", this.Name, this.Age);
}

public int CompareTo(object obj)
{
Person p = obj as Person;
return this.Age.CompareTo(p.Age);
}
}
static void Main(string[] args)
{

List<Person> persons = new List<Person>();
persons.Add(new Person() { Name = "ALin", Age = 13 });
persons.Add(new Person() { Name = "John", Age = 34 });
persons.Add(new Person() { Name = "Lee", Age = 26 });
persons.Add(new Person() { Name = "Kui", Age = 47 });
persons.Add(new Person() { Name = "Meimei", Age = 45 });

persons.Sort();

foreach (Person item in persons)
{
Console.WriteLine(item.ToString());
}

Console.ReadKey();
}


执行结果:



那么,问题来了。如果我们不想使用Age排序,或者Person的代码已经生成DLL等原因导致我们无法修改,现在要使用Name进行排序,这时IComparer的作用就来了。

可以使用IComparer实现一个比较器。

class SortByName : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
}
}


在排序时为Sort方法提供此比较器

persons.Sort(new SortByName());


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐