C# 排序列表<&燃气轮机;orderby列表<;字符串>;计数
我有一张这样的清单C# 排序列表<&燃气轮机;orderby列表<;字符串>;计数,c#,C#,我有一张这样的清单 List<Category> list = Category.getCategoryList(); List List=Category.getCategoryList(); 在类别类中,我有公共列表子类别{get;set;},有些类别有子类别,有些没有子类别,我想按子类别对列表排序。其中带有子类别的类别位于第一位。 我知道这将按猫名排序 List<Category> SortedList = list.OrderBy(o => o.catN
List<Category> list = Category.getCategoryList();
List List=Category.getCategoryList();
在类别类中,我有公共列表子类别{get;set;}
,有些类别有子类别,有些没有子类别,我想按子类别对列表排序。其中带有子类别的类别位于第一位。
我知道这将按猫名排序
List<Category> SortedList = list.OrderBy(o => o.catName).ToList();
List-SortedList=List.OrderBy(o=>o.catName.ToList();
如果列表中有子类别,如何按子类别排序。
欢迎提供任何帮助。您可以按子类别的计数进行排序,这样您将首先获得包含更多子类别的类别:
var sorted = list.OrderByDescending(o => o.subCat != null ? o.subCat.Count : 0).ToList();
如果要按类别名称排序并首先显示带有子类别的类别,则可以使用,然后使用:
var sorted = list
.OrderBy(o => o.subCat != null && o.subCat.Count > 0 ? 0 : 1)
.ThenBy(o => o.catName)
.ToList();
您可以按子类别的计数进行排序,这样您将拥有第一个具有更多子类别的类别:
var sorted = list.OrderByDescending(o => o.subCat != null ? o.subCat.Count : 0).ToList();
如果要按类别名称排序并首先显示带有子类别的类别,则可以使用,然后使用:
var sorted = list
.OrderBy(o => o.subCat != null && o.subCat.Count > 0 ? 0 : 1)
.ThenBy(o => o.catName)
.ToList();
如果要按子类别的存在进行排序,请使用排序谓词Any
方法:
//will order by the boolean value - due to the descending first the "true" and then "false"
var result = OrderByDescending(item => item.SubCat.Any());
如果要按总和类别的数量排序:
var result = OrderByDescending(item => item.SubCat.Count());
对于按多个属性排序,请使用然后按如果要按子类别的存在进行排序,请使用任何方法:
//will order by the boolean value - due to the descending first the "true" and then "false"
var result = OrderByDescending(item => item.SubCat.Any());
如果要按总和类别的数量排序:
var result = OrderByDescending(item => item.SubCat.Count());
要按多个属性排序,请使用然后使用