public class Student { public string Id { get; set; } public string Name { get; set; } public override bool Equals(object obj) { Student e = obj as Student; return this.Id == e.Id && this.Name == e.Name; } public override int GetHashCode() { return this.Id.GetHashCode() * 100 + this.Name.GetHashCode(); } }
public static void Test() { var hashSetData = new HashSet<Student>(); hashSetData.Add(new Student { Id = "001", Name = "张三" }); hashSetData.Add(new Student { Id = "002", Name = "李四" }); hashSetData.Add(new Student { Id = "001", Name = "张三" }); hashSetData.Add(new Student { Id = "003", Name = "张三" }); foreach (var item in hashSetData) { Console.WriteLine("Id:{0},Name:{1}", item.Id, item.Name); } }