現在有一個類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綁定,適合比較方法經常變化的類。但是代碼比較復雜
方法二恰恰相反。比較方法與類綁定。但是比較簡潔