一、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); }