标签:
C#集合实现去重,交集,差集等,用到比较时,有几种方式可以满足。
数据:
var list = new List<MyClass> { new MyClass {MyProperty1 = "10", MyProperty2 = "20" }, new MyClass {MyProperty1 = "10", MyProperty2 = "30" }, new MyClass {MyProperty1 = "20", MyProperty2 = "20" } };
方法一:
public class MyClass { public string MyProperty1 { get; set; } public string MyProperty2 { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(obj, null)) return false; if (ReferenceEquals(this, obj)) return true; var o = obj as MyClass; return o.MyProperty1.Equals(o.MyProperty1); } public override int GetHashCode() { return MyProperty1.GetHashCode(); } }
用法:
list.Distinct();//去重
方法二:
public class MyClass : IEquatable<MyClass> { public string MyProperty1 { get; set; } public string MyProperty2 { get; set; } public bool Equals(MyClass other) { if (ReferenceEquals(other, null)) return false; if (ReferenceEquals(this, other)) return true; return MyProperty1.Equals(other.MyProperty1); } }
用法:
list.Distinct();//去重
方法三:
public class MyClass { public string MyProperty1 { get; set; } public string MyProperty2 { get; set; } } public class MyClassIEqualityComparer : IEqualityComparer<MyClass> { public bool Equals(MyClass x, MyClass y) { if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (ReferenceEquals(x, y)) return true; return x.MyProperty1.Equals(y.MyProperty1); } public int GetHashCode(MyClass obj) { return obj.MyProperty1.GetHashCode(); } }
用法:
list.Distinct(new MyClassIEqualityComparer());//去重
标签:
原文地址:http://www.cnblogs.com/quxian/p/5692887.html