2014年4月21日 星期一

{LInQ} 做Dictionary、Distinct ... 多屬性為Key 比對其Class覆寫方法

如需要將多個屬性做為Key供判斷,需要另外覆寫 Equals()與 GetHashCode() 才能達到判斷是否相同的結果....

        public class InventoryWODetail
        {
            public int SOItemId { set; get; }

            public string CPSPN { set; get; }

            public string WONo { set; get; }

            public int WOTotalQty { set; get; }

            public int WOCloseQty { set; get; }

            public int WOOpenQty { set; get; }

            public string CPSSONo { set; get; }

            public string CPSSOPlannedShipDate { set; get; }

            public string WOPlannedClose { set; get; }

            public override bool Equals(object obj)
            {
                if (!(obj is InventoryWODetail))
                    return false;
                else
                {
                    InventoryWODetail other = obj as InventoryWODetail;
                    return (other.SOItemId == this.SOItemId && other.CPSPN == this.CPSPN && other.WONo == this.WONo && other.WOTotalQty == this.WOTotalQty
                        && other.WOCloseQty == this.WOCloseQty && other.WOOpenQty == this.WOOpenQty && other.CPSSONo == this.CPSSONo && other.CPSSOPlannedShipDate == this.CPSSOPlannedShipDate
                        && other.WOPlannedClose == this.WOPlannedClose);
                }
            }

            public override int GetHashCode()
            {
                return string.Format("{0} | {1} | {2} | {3}  | {4}  | {5}  | {6}  | {7}  | {8} ", this.SOItemId, this.CPSPN, this.WONo, this.WOTotalQty, this.WOCloseQty, this.WOOpenQty, this.CPSSONo, this.CPSSOPlannedShipDate, this.WOPlannedClose).GetHashCode();
            }
        }


參考資訊:http://www.cnblogs.com/626498301/archive/2011/02/24/1963413.html