zoukankan      html  css  js  c++  java
  • 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 逆序:

     

  • 相关阅读:
    SVN
    jenkins可视化
    Tomcat
    防火墙
    keepalived
    MHA高可用
    http
    inotifywait
    DNS
    nginx
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/9505994.html
Copyright © 2011-2022 走看看