当我们用泛型list存储了一系列数据,而要求以某一个字段作为排序对象时,可以用很多方法去实现。
1.实现接口IComparer<*>(泛型情况)
2.用委托实现
3.Lambda表达式
4.扩展方法
class human:IComparer<human>
{
private string name;
public string Name
{
set
{
Console.WriteLine("被调用");
name = value;
}
get { return name; }
}
public int No;
public human()
{
}
public human(string name)
{
Name = name;
}
public int Compare(human x, human y)
{
return x.name.CompareTo(y.name);
}
}
class humanSort:IComparer<human>
{
public int Compare(human x, human y)
{
return x.Name.CompareTo(y.Name);
}
}
public static void Main(string[] args)
{
human h1 = new human("Jack");
h1.Name = "Sam";
human h2 = new human();
h2.Name = "Zara";
Console.WriteLine(h2.Name==null);
Console.WriteLine(h2.No);
List<human> list = new List<human>();
human h3 = new human("Alin");
list.Add(h1);
list.Add(h2);
list.Add(h3);
IComparer<human> humancom = new human();
//实现接口
//list.Sort(humancom);
//委托
//list.Sort(delegate(human x, human y) {return x.Name.CompareTo(y.Name);});
//Lambda
//list.Sort((x,y)=>y.Name.CompareTo(x.Name));
//扩展方法
/*foreach (var VARIABLE in list.OrderBy(p=>p.Name))
{
Console.WriteLine(VARIABLE.Name);
}*/
foreach (var human in list)
{
Console.WriteLine(human.Name);
}
}