怎么求两个List<model>的差集呢
List<AddDeleteApprovers> oldAppovers = new List<AddDeleteApprovers>(); List<AddDeleteApprovers> newAppovers = new List<AddDeleteApprovers>(); oldAppovers.Add(new AddDeleteApprovers { approverId = "a", approverName = "name" }); oldAppovers.Add(new AddDeleteApprovers { approverId = "b", approverName = "name" }); oldAppovers.Add(new AddDeleteApprovers { approverId = "c", approverName = "name" }); newAppovers.Add(new AddDeleteApprovers { approverId = "b", approverName = "name" }); newAppovers.Add(new AddDeleteApprovers { approverId = "c", approverName = "name" }); newAppovers.Add(new AddDeleteApprovers { approverId = "d", approverName = "name" });
oldAppovers.Except(newAppovers).ToList().ForEach(p => { Response.Write(p.approverId + ":" + p.approverName); }); //删除的
public class AddDeleteApprovers
{
public string approverId { get; set; }
public string approverName { get; set; }
}
打印出来的还是a b c ,我要的结果是 a
基于你目前的实现代码,电脑是不知道
oldAppovers.Add(new AddDeleteApprovers { approverId = "a", approverName = "name" }); oldAppovers.Add(new AddDeleteApprovers { approverId = "b", approverName = "name" });
与
newAppovers.Add(new AddDeleteApprovers { approverId = "b", approverName = "name" }); newAppovers.Add(new AddDeleteApprovers { approverId = "c", approverName = "name" });
是相等的。
你需要通过重载AddDeleteApprovers的GetHashCode()与Equals(object obj)方法告诉电脑:
public class AddDeleteApprovers { public string approverId { get; set; } public string approverName { get; set; } public override int GetHashCode() { return this.approverId.GetHashCode(); } public override bool Equals(object obj) { return this.approverId == (obj as AddDeleteApprovers).approverId; } }
恩。是的。是要重写GetHashCode()与Equals(object obj)
public class AddDeleteApprovers : IEquatable<AddDeleteApprovers>
{
public string approverId { get; set; }
public string approverUvid { get; set; } //java ID 长串
public string approverName { get; set; }
public bool Equals(AddDeleteApprovers other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return approverId.Equals(other.approverId);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
////Get hash code for the Name field if it is not null.
//int hashApproverId = approverId == null ? 0 : approverId.GetHashCode();
////Get hash code for the Code field.
//int hashApproverName = approverName.GetHashCode();
////Calculate the hash code for the product.
//return hashApproverId ^ hashApproverName;
return 0;
}
}
为啥不用where呢??
http://www.soaspx.com/dotnet/csharp/csharp_20121204_9884.html
路过学习
.Net高级部落(101380580) 开立分群了,欢迎各位志同道合的技术人员加入!
你这样肯定是abc啊,Except掉了new的那个,剩下的就是old那个的abc了。
只能是循环,循环判断,发生false的时候,就messagebox出来
except是哪个包下的,具体怎么用