Plazza Sele Plazza Sele - 3 years ago 150
C# Question

Sort List<> orderby list<string> count

I have a list like this

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

In Category class I have
public List<string> subCat { get; set; }
, Some categories have subCat and some doesn't have, I want to order my list by subCat. where the categories with subCat comes first.
I know that this will sort by catName

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

How can I sort by subCat where there is subCat in the list.
Any help would be appricaited.

Answer Source

You can sort by the count of the subcategories so you will have first the categories with more children:

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

If you want to order by category name AND first show the categories with subcategories you can use ThenBy:

var sorted = list
                .OrderBy(o => o.subCat != null && o.subCat.Count > 0 ? 0 : 1)
                .ThenBy(o => o.catName)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download