2016-08-14 67 views
0

我有这样排序列表<>排序依据列表<string>计数

List<Category> list = Category.getCategoryList(); 

在Category类我有public List<string> subCat { get; set; }列表,某些类别具有SUBCAT,有些没有,我想订购由SUBCAT我的列表。带有subCat的类别排在第一位。 我知道,这将catName

List<Category> SortedList = list.OrderBy(o => o.catName).ToList(); 

排序我如何排序SUBCAT那里是在列表中SUBCAT。 任何帮助将被appricaited。

回答

1

您可以通过子类别的数量排序,所以你必须先与更多的孩子类别:

var sorted = list.OrderByDescending(o => o.subCat != null ? o.subCat.Count : 0).ToList(); 

如果要通过类别名称和订购首先展示你可以使用ThenBy子类别的类别:

var sorted = list 
       .OrderBy(o => o.subCat != null && o.subCat.Count > 0 ? 0 : 1) 
       .ThenBy(o => o.catName) 
       .ToList(); 
1

如果要通过子类的存在排序使用的排序谓词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()); 

对于排序由几个属性使用ThenBy