实际项目中经常用到 Union,Distinct,INtersect,Execpt对列表进行处理
一般来说要首先重写 Equals 和GetHashCode方法
首先看为重写的情况:
namespace LinqCookBook { class Program { static void Main(string[] args) { var model1 = new List<model> { new model(){name = "1"}, new model(){name="2"}, new model(){name = "3"} }; var model2 = new List<model> { new model() {name = "1"}, new model() {name = "2"}, new model() {name = "3"} }; var list = model1.Union(model2).Distinct(); foreach (var item in list) { Console.WriteLine(item.name); } } } public class model { public string name { get; set; } //public override bool Equals(object obj) //{ // return obj.GetHashCode().Equals(this.GetHashCode()); //} //public override int GetHashCode() //{ // return this.name.GetHashCode(); //} } }
运行结果:
重写后:
namespace LinqCookBook { class Program { static void Main(string[] args) { var model1 = new List<model> { new model(){name = "1"}, new model(){name="2"}, new model(){name = "3"} }; var model2 = new List<model> { new model() {name = "1"}, new model() {name = "2"}, new model() {name = "3"} }; var list = model1.Union(model2).Distinct(); foreach (var item in list) { Console.WriteLine(item.name); } } } public class model { public string name { get; set; } public override bool Equals(object obj) { return obj.GetHashCode().Equals(this.GetHashCode()); } public override int GetHashCode() { return this.name.GetHashCode(); } } }
运行结果:
原因:
当元素比较时,会使用默认规则比较,通过equals和gethashcode来确定应用类的一个实例和另一个实例是否相同。通常是不相同的,因为他们指向了不同的内存地址,导致哈希值是不同的。重写以后,认为某些属性值相同则认为相同。
时间: 2024-10-12 20:29:34