gpt4 book ai didi

c# - 比较两个对象的值而不列出每一列

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:36 24 4
gpt4 key购买 nike

Web 服务导入数据并存储在业务逻辑 Graph.AddressList 中。如果找到匹配项,则添加到 keepList。问题是数据完全相同,但没有添加到保留列表中。例如,数据库中记录中的 ENTITYKEY 会被填充,但不会在 Xml 中填充,而无需写出数据库中的每一列以匹配 xmlRecord 中的每一列。有解决办法吗?

// Fetch List Of Addresses
List<Address> updateAddressList = DbContext.GraphAddressList.Where<Address>(p => p.PersonnelNo == action.PersonnelNo).ToList<Address>();

////IF ADDRESS EXISTS IN THE DB, BUT NOT IN THE XML FILE, REMOVE FROM DB
List<Address> keepList = new List<Address>();
foreach (Address recordInDB in updateAddressList)
{
foreach (Address_0006 recordInXML in Graph.AddressList)
{
if (recordInDB == recordInXML)
{
keepList.Add(recordInDB);
}
}
}

List<Address> removeList = updateAddressList.Except(keepList).ToList();
foreach (Address record in removeList)
{
DbContext.AddressList.DeleteObject(record);
}

感谢您的回复,所以我真的需要创建一个类

 public override bool Equals(object obj)
{
var item = obj as RecommendationDTO;

if (item == null)
{
return false;
}

return this.RecommendationId.Equals(item.RecommendationId);
}

public override int GetHashCode()
{
return this.RecommendationId.GetHashCode();
}

最佳答案

recordInDBrecordInXML是自定义对象,要检查它们是否相等,您必须:

  1. 覆盖 EqualsGetHashCode对于他们:Correct way to override Equals() and GetHashCode()
  2. 实现 IEqualityComparer : How to use the IEqualityComparer
  3. 让你的一个类(class)实现IEquatable<T>其中 T是其他类的类型

这样做,对象将根据它们具有的属性进行比较。目前 ( x == y ) 检查的是引用是否相等——这是两个不同的实例意味着 false .这样做之后,比较时你也应该使用 recordInDB.Equals(recordInXML)

实现之后你还可以重构一下:

var keepList = recordInDB.Where(record => Graph.AddressList.Contains(record));
var removeList = updateAddressList.Except(keepList).ToList();
foreach (Address record in removeList)
{
DbContext.AddressList.DeleteObject(record);
}

然后在您的 Address_0006 中选择选项 3实现IEquatable<Address> :

public class Address_0006 : IEquatable<Address>
{
public bool Equals(Address other)
{
// Compare here that each of the relevant properties in this (Address_0006)
// equals the corresponding property in other (Address)
}
}

关于c# - 比较两个对象的值而不列出每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45932282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com