清单以特定方式排序

时间:2018-06-24 18:41:30

标签: c# list linq sorting

public class Program
 {
    static void Main(string[] args)
    {
        List<Category> categoryList = new List<Category>()
        {
            new Category(){CategoryType = "BP"},
            new Category(){ CategoryType ="BY"},
            new Category(){ CategoryType ="BT1"},
            new Category(){ CategoryType ="BT3"},
            new Category(){ CategoryType ="BTU"},
            new Category(){ CategoryType ="BT2"},
        };
        categoryList = categoryList.OrderBy(x => x.CategoryType).ToList();
        categoryList.ForEach(item => Console.WriteLine(item.CategoryType));
        Console.ReadKey();
    }
    public class Category
    {
        public string CategoryType { get; set; }
        public int Count { get; set; }
    }
}

通过上述程序,我得到的结果像P

BT1
BT2
BT3
BTU
BY

但是我希望结果为BP, BY, BT1, BT2, BT3,BTU

1 个答案:

答案 0 :(得分:3)

您可以按类别名称的长度,然后按其值排序:

categoryList =
    categoryList.OrderBy(x => x.CategoryType.Length).ThenBy(x => x.CategoryType).ToList();