C# 中集合类型需要按多个条件排序

在 C# (.net 3.5 之后) 中集合是可以通过 OrderBy() 和 OrderByDescending()方法来进行排序的,
如果需要集合中的元素是对象,还可以通过 Lambda表达式进行按属性排序,如:
定义一个学生类:

    class student
        {
            public int id { get; set; }
            public string name { get; set; }
            public string hometown { get; set; }

            public student(int id, string name, string hometowm)
            {
                this.id = id;
                this.name = name;
                this.hometown = hometown;
            }
        }

 

按学生名字排序,如果同名的,则按学号升序排序:

     List<student> list = new List<student>() {
                new student(101, "olivia", "shantou"),
                new student(102, "sarah","shanghai"),
                new student(103, "nani", "china"),
                new student(104, "tommy", "maoming"),
                new student(105, "tommy", "shandong"),
            };

        listBox.ItemsSource = list.OrderBy(x => x.name); // just order by name
        listBox2.ItemsSource = list.OrderBy(x => x.name).ThenByDescending(x => x.id); // order by name, and then order desc by id

        }

由上可见,多个条件时使用的是 ThenBy() 以及 ThenByDescending() 方法

 

结果:
只按 name 排序:

先按 name 排序,再按 id 逆序:

 

 

posted @ 2018-08-20 15:52  一菲聪天  阅读(3224)  评论(2编辑  收藏  举报