2013年1月28日 星期一

[C#] 快速比對兩個自訂 List 的差異

首先,要先將該 class 後面補上: IEquatable 並寫覆寫它的 Equals & GetHashCode 這兩支函數
        // 宣告物件的結構
        public class Obj : IEquatable
        {
            //物件名稱
            public string objTitle { get; set; }
            //物件連結
            public string objURL { get; set; }
            //物件所在地
            public string objAddr { get; set; }
            // 物件種類
            public string objKind { get; set; }
            //物件單價
            public string objPrice { get; set; }
            //物件類別
            public string objClass { get; set; }
            //物件坪數
            public string objBuild { get; set; }
            //物件總價
            public string objTotalPrice { get; set; }


            public bool Equals(Obj other)
            {
                //Check whether the compared object is null.
                if (Object.ReferenceEquals(other, null)) return false;

                //Check whether the compared object references the same data.
                if (Object.ReferenceEquals(this, other)) return true;

                //Check whether the properties are equal.
                return objURL.Equals(other.objURL) && 
                    objTitle.Equals(other.objTitle) &&
                    objAddr.Equals(other.objAddr) &&
                    objKind.Equals(other.objKind) &&
                    objPrice.Equals(other.objPrice) &&
                    objClass.Equals(other.objClass) &&
                    objBuild.Equals(other.objBuild) &&
                    objTotalPrice.Equals(other.objTotalPrice);
            }


            public override int GetHashCode()
            {
                // 因為這些變數都是 String 型態的, 所以要判斷是不是 null
                // 如果是其它型態的話, 可以直接 .GetHashCode
                // int hashAge = Age.GetHashCode();

                int hashobjURL = objURL == null ? 0 : objURL.GetHashCode();
                int hashobjTitle = objTitle == null ? 0 : objTitle.GetHashCode();
                int hashobjAddr = objAddr == null ? 0 : objAddr.GetHashCode();
                int hashobjKind = objKind == null ? 0 : objKind.GetHashCode();
                int hashobjPrice = objPrice == null ? 0 : objPrice.GetHashCode();
                int hashobjClass = objClass == null ? 0 : objClass.GetHashCode();
                int hashobjBuild = objBuild == null ? 0 : objBuild.GetHashCode();
                int hashobjTotalPrice = objTotalPrice == null ? 0 : objTotalPrice.GetHashCode();

                // 回傳的部分我還是沒有很理解
                // 我的認知是 GetHashCode() 主要是回傳一個該物件的唯一碼
                // 所以 return 的部分, 就是看如何產生了=_=
                //Calculate the hash code.
                return (hashobjURL + hashobjTitle + hashobjAddr + hashobjKind + hashobjPrice + hashobjClass + hashobjBuild + hashobjTotalPrice);
            }
        }
產生比對:
DiffDataList = ObjDataList.Except(OldDataList).ToList();
別忘了,記得
using System.Linq;
沒有 using 這個 Linq,就沒辦法使用 Except 啦! 所以這應該也算是使用 Linq 去尋找差異吧=_=??

沒有留言: