# 泛型集合排序问题

0

namespace ABC
{
class Program
{
static void Main(string[] args)
{
List<Contact> list = new List<Contact>() { new Contact(){FirstName="A",LastName="B"},
new Contact(){FirstName="A",LastName="A"},new Contact(){FirstName="A",LastName="C"},
};
//Compare(Contact x, Contact y)怎么把写好的方法带入下面的红色函数
list = list.Sort(“函数”);

}
}
class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class NameCompare : IComparer<Contact>
{
public int Compare(Contact x, Contact y)
{
int result;
if (Contact.ReferenceEquals(x, y))
{
result = 0;
}
else
{
if(x==null)
{
result=1;
}
else if (y == null)
{
result = -1;
}
else
{
result = StringCompare(x.LastName, y.LastName);
if(result==0)
{
result=StringCompare(x.FirstName,y.FirstName);
}
}
}
return result;
}
private static int StringCompare(string x, string y)
{
int result;
if (x == null)
{
if (y == null)
{
result = 0;
}
else
{
result = 1;
}
}
else
{
result = x.CompareTo(y);
}
return result;
}
}
}

0

list.Sort有三个重载，这个是其中之一，按照你的定义，你可以：

ICompare compare = new NameCompare();

list.Sort(compare);

519740105 | 大侠五级 |园豆：5810 | 2014-09-05 06:34

Yeah！

ICompare compare = new NameCompare();

list.Sort(compare);

IComparer<Contact> compare = new NameCompare();

list.Sort(compare);

@小艾123: 豆是小事，尊重与理解第一。

519740105 | 园豆：5810 (大侠五级) | 2014-09-06 21:15

@519740105: 恩恩

@小艾123: :)

0

new NameCompare()

您需要登录以后才能回答，未注册用户请先注册