• 顺序表(list)对类对象排序


    可以使用实现比较接口的方法,直接用sort排序。

    如c#:

    class Person1:IComparable<Person1>
        {
            public string Xm { get; set; }
            public int Nl { get; set; }
            public int CompareTo(Person1 obj)
            {
                return Nl - obj.Nl;
            }
        }

    主程序:

    var a = new List<Person1>();
                a.Add(new Person1() { Xm = "d", Nl = 20 });
                a.Add(new Person1() { Xm = "c", Nl = 40 });
                a.Add(new Person1() { Xm = "b", Nl = 10 });
                a.Add(new Person1() { Xm = "a", Nl = 30 });
                a.Sort();
                foreach (var item in a)
                {
                    Console.Write($"Name:{item.Xm},Age:{item.Nl}	");
                }

    运行结果:

     ---------------------------------------------------------

    对于java: 

    public class Person1 implements Comparable<Person1>
    {
        public String Xm;
        public int Nl;
    
        public Person1(String x,int y)
        {
            Xm=x;
            Nl=y;
        }
        public int compareTo(Person1 obj)
        {
            return Nl - obj.Nl;
        }
    }

    主程序:

     public static void main(String[] args) throws Exception
        {
            var a = new ArrayList<Person1>();
            a.add(new Person1("d",20));
            a.add(new Person1("c",40));
            a.add(new Person1("b",10));
            a.add(new Person1("a",30));
            a.sort(Comparator.naturalOrder());//升序
            for (Person1 item : a)
            {
                System.out.print("Name:"+item.Xm+",Age:"+item.Nl+"	");
            }
        }

    运行结果:


    c#还可以用lamda表达式指定比较器方法,排序:

    Person1类:

    主程序:

     运行结果:

     JAVA也有类似方法,此处略。

  • 相关阅读:
    Hive 常用的开窗函数
    常见的三类范式
    About A ROS driver for TCP/IP modems
    ROS Package for communication over TCP/IP.
    A repo of awesome papers about multi target multi camera tracking
    分布式锁
    http请求跳过ssl证书(Get请求示例)
    mysql和mogodb特殊字符转义
    全局异常捕捉
    Jasypt加密
  • 原文地址:https://www.cnblogs.com/wanjinliu/p/13973962.html
Copyright © 2020-2023  润新知