簡體   English   中英

C#列表比較忽略類項

[英]C# List comparison ignoring class item

我有兩個數據庫DB1和DB2,我從中檢索銷售訂單並進入列表。 我現在想要找到DB1中缺少的銷售訂單,以便將它們添加到DB2中

我有listDB1形式的listDB1ListDB2

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM