C# 實現Sort介面 排序自定義實體類集合
阿新 • • 發佈:2019-02-03
預定義實體類
class SortClass
{
public SortClass(int id,String value)
{
this.Id = id;
this.Value = value;
}
String _Value = String.Empty;
public String Value
{
get { return _Value; }
set { _Value = value; }
}
int _Id = 0;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
}
測試方法
private static void sorttest()
{
List<SortClass> sortlist = new List<SortClass>();
sortlist.Add(new SortClass(5, "v5"));
sortlist.Add(new SortClass(3, "v3"));
sortlist.Add(new SortClass(4, "v4"));
sortlist.Add(new SortClass(5, "v5"));
sortlist.Add(new SortClass(77, "v77"));
Console.WriteLine("排序前");
Console.WriteLine (String.Join("\n", from a in sortlist select String.Format("id:{0}\tvalue:{1}", a.Id, a.Value)));
Console.WriteLine("排序後");
sortlist.Sort(SortFunc);
Console.WriteLine(String.Join("\n", from a in sortlist select String.Format("id:{0}\tvalue:{1}", a.Id, a.Value)));
}
Sort函式實現
private static int SortFunc(SortClass x, SortClass y)
{
if(x.Id>y.Id)
{
return 1;
}
else if(x.Id == y.Id)
{
return 0;
}
return -1;
}
測試結果