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 逆序:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值