我有两个数据库DB1和DB2,我从中检索销售订单和列表。我现在想要找到DB2中缺少的DB1中的销售订单,以便将它们添加到DB2
我的格式为listDB1
和ListDB2
:
public class SalesOrder
{
public int docNum;
public string cardCode;
public string cardName;
public DateTime docDate;
public DateTime docDueDate;
public double docTotal;
public int lineItemCount;
public string comments;
}
我现在想要比较两个列表忽略docNum
的两个列表,这两个列表是在比较其余元素时自动生成的。使用:
unaddedSOs = listDB1.Except(listDB2).ToList();
比较所有包括docNum。我如何实现我的需求,以便获得未添加的文档编号?
答案 0 :(得分:4)
您可以实施IEquatable<SalesOrder>
,也可以创建自定义IEqualityComparer<SalesOrder>
。请注意,我还建议您将这些公共字段转换为属性。
public class SalesOrder : IEquatable<SalesOrder>
{
public int DocNum { get; set; }
public string CardCode { get; set; }
public string CardName { get; set; }
public DateTime DocDate { get; set; }
public DateTime DocDueDate { get; set; }
public double DocTotal { get; set; }
public int LineItemCount { get; set; }
public string Comments { get; set; }
public bool Equals(SalesOrder other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(cardCode, other.cardCode) &&
string.Equals(cardName, other.cardName) &&
docDueDate.Equals(other.docDueDate) &&
docTotal.Equals(other.docTotal) &&
lineItemCount == other.lineItemCount &&
string.Equals(comments, other.comments);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((SalesOrder) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (cardCode != null ? cardCode.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (cardName != null ? cardName.GetHashCode() : 0);
hashCode = (hashCode*397) ^ docDueDate.GetHashCode();
hashCode = (hashCode*397) ^ docTotal.GetHashCode();
hashCode = (hashCode*397) ^ lineItemCount;
hashCode = (hashCode*397) ^ (comments != null ? comments.GetHashCode() : 0);
return hashCode;
}
}