• 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);
    }

  • 相关阅读:
    代理模式
    建造者模式
    开源版本 hadoop-2.7.5 + apache-hive-2.1.1 + spark-2.3.0-bin-hadoop2.7整合使用
    Phoenix映射HBase数据表
    使用sqoop将mysql中表导入hive中报错
    数据库索引原理及优化(转载)
    6.JAVA知识点归纳整理
    5.hbase表新增数据同步之add_peer
    mongodb分布式集群搭建
    4.HBASE数据迁移方案(之snapshot):
  • 原文地址:https://www.cnblogs.com/lunawzh/p/16410746.html
Copyright © 2020-2023  润新知