• C# List 、 HashSet类去重


    一、HashSet去重

    1、对简单类型的去重

    HashSet<int> ints = new HashSet<int>() { 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1};
    
    foreach (var item in ints)
    {
        Console.WriteLine(item);
    }

     2、对象集合去重

    class person
    {
        public string name { get; set; }
        public string   sex { get; set; }
        public byte age { get; set; }
    
        public override bool Equals(object? obj)
        {
            var o=obj as person;
            return this.name == o.name;
        }
        public override int GetHashCode()
        {
            return this.name.GetHashCode();
        }
        public override string ToString()
        {
            return $"{name}:{age}:{sex}";
        }
    }
    HashSet<person> p = new HashSet<person>();
    p.Add(new person { name = "张三", age = 11, sex = "" });
    p.Add(new person { name = "李四", age = 11, sex = "" });
    p.Add(new person { name = "王五", age = 11, sex = "" });
    p.Add(new person { name = "张三", age = 11, sex = "" });
    p.Add(new person { name = "王五", age = 11, sex = "" });
    foreach (var item in p)
    {
        Console.WriteLine(item);
    }

    二、List去重

    List<person> p = new List<person>();
    p.Add(new person { name = "张三", age = 11, sex = "" });
    p.Add(new person { name = "李四", age = 11, sex = "" });
    p.Add(new person { name = "王五", age = 11, sex = "" });
    p.Add(new person { name = "张三", age = 11, sex = "" });
    p.Add(new person { name = "王五", age = 11, sex = "" });
    foreach (var item in p.DistinctBy(x=>x.name))
    {
        Console.WriteLine(item);
    }

  • 相关阅读:
    流体力学笔记 第二章 流体力学的基本概念
    jvm常用的参数
    链表的反转
    数据流中的中位数
    二叉树对称
    二叉树镜像
    输入框校验
    判断单选或者复选框中选中的值
    网页中window.open 弹出 父页面和子页面数值交互
    数组去重
  • 原文地址:https://www.cnblogs.com/lunawzh/p/16410746.html
Copyright © 2020-2023  润新知