List.Sort方法的二级排序

Bot*_*ous 1 c# asp.net sorting

我有一个通用列表,我试图实现二级排序类型.我可以通过一种类型对其进行排序,但无法进行二次排序.

这是我正在使用的:

当我打电话排序:

List<Totals> totals = new LoadTotalList();
totals.Sort(Totals.Status); 
Run Code Online (Sandbox Code Playgroud)

这是Totals类:

public class Totals
{
  public string Status { get; set; } 
  public string Total { get; set; } 
  public string Cost { get; set; } 

  public static Comparison<Totals> StatusComp = 
delegate(Totals item1, Totals item2)
{
 return item1.Status.CompareTo(item2.Status);
};

  public static Comparison<Totals> CostComp = 
delegate(Totals item1, Totals item2)
{
 return item1.Cost.CompareTo(item2.Cost);
};


}
Run Code Online (Sandbox Code Playgroud)

我试过排序第一种类型,然后排序第二种类型,但似乎无法获得二级排序类型.我知道可以使用OrderBy子句然后使用ThenBy Clause来完成Linq.但我还有其他选择吗?在此先感谢您的帮助!

Jon*_*eet 6

创建一个Comparison<T>具有主要比较然后是次要比较的内容非常简单:

public static class Comparisons
{
    public static Comparison<T> Then<T>(this Comparison<T> primary,
                                        Comparison<T> secondary)
    {
        // TODO: Nullity validation
        return (x, y) =>
        {
            int first = primary(x, y);
            return first != 0 ? first : secondary(x, y);
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

list.Sort(Totals.StatusComp.Then(Totals.CostComp));
Run Code Online (Sandbox Code Playgroud)

(您也可以IComparer<T>轻松地做同样的事情.)