现在有一个类Contact
class Contact
{
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _FirstName;
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _LastName;
}
对类型排序有两种方法:
1、给sort函数传递一个IComparer<Contact>参数
class Contact
{
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _FirstName;
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _LastName;
public Contact(string first, string last)
{
_FirstName = first;
_LastName = last;
}
}
class ContactComparer : IComparer<Contact>
{
public int Compare(Contact c1, Contact c2)
{
int result;
if (Contact.ReferenceEquals(c1, c2))
{
result= 0;
}
else
{
if (c1 == null)
{
result = 1;
}
else if (c2 == null)
{
result = -1;
}
else
{
result = c1.LastName.CompareTo(c2.LastName);
if (result == 0)
{
result = c1.FirstName.CompareTo(c2.FirstName);
}
}
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
List<Contact> list = new List<Contact>();
list.Add(new Contact("wang","guang"));
list.Add(new Contact("li", "he"));
list.Add(new Contact("zhao", "ti"));
list.Sort(new ContactComparer());
}
}
2、让Contact实现IComparable接口
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
namespace Happy
{
class Contact:IComparable<Contact>
{
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _FirstName;
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _LastName;
public Contact(string first, string last)
{
_FirstName = first;
_LastName = last;
}
public int CompareTo(Contact c)
{
int result;
result = _LastName.CompareTo(c._LastName);
if (result == 0)
{
result = _FirstName.CompareTo(c._FirstName);
}
return result;
}
}
class ContactComparer : IComparer<Contact>
{
public int Compare(Contact c1, Contact c2)
{
int result;
if (Contact.ReferenceEquals(c1, c2))
{
result= 0;
}
else
{
if (c1 == null)
{
result = 1;
}
else if (c2 == null)
{
result = -1;
}
else
{
result = c1.LastName.CompareTo(c2.LastName);
if (result == 0)
{
result = c1.FirstName.CompareTo(c2.FirstName);
}
}
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
List<Contact> list = new List<Contact>();
list.Add(new Contact("wang","guang"));
list.Add(new Contact("li", "he"));
list.Add(new Contact("zhao", "ti"));
//list.Sort(new ContactComparer());
list.Sort();
}
}
}
方法一的好处是比较方法没有与类Conta绑定,适合比较方法经常变化的类。但是代码比较复杂
方法二恰恰相反。比较方法与类绑定。但是比较简洁