[英]C# List comparison ignoring class item
我有两个数据库DB1和DB2,我从中检索销售订单并进入列表。 我现在想要找到DB1中缺少的销售订单,以便将它们添加到DB2中
我有listDB1
形式的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。 我如何实现我的需要,以便获得未添加的文档编号?
您可以实现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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.