[筆記]C# 用Except做差集資料比對 實作紀錄

遇到要做兩的LIST的比對尤其是資料很多的時候

可以藉由Except(差集)來完成任務

簡易比對兩個文字LIST
 

void Main()
{
	List<string> oldList = new List<string>(new string[] { "1", "2", "3" });
	List<string> newList = new List<string>(new string[] { "2", "4", "6" });

	Console.WriteLine("找出newList中跟oldList有差異的資料");
	var diffList1 = newList.Except(oldList);
	foreach(var item in diffList1){
		Console.WriteLine(item);
	}
	
	Console.WriteLine("找出oldList中跟newList有差異的資料");
	var diffList2 = oldList.Except(newList);
	foreach(var item in diffList2){
		Console.WriteLine(item);
	}
}

比對結果

假設有遇到比較複雜的比對

就需要在第2個參數欄位填入自己定義的IEqualityComparer物件來比對兩個序列的差異

首先建立IEqualityComparer的部分

public class CompareModel
{
	public int? uId { get; set; }
    public string uName { get; set; }
    public int? uAge { get; set; }
}
public class DataComparer : IEqualityComparer<CompareModel>
{
    public bool Equals(CompareModel x, CompareModel y)
    {
        //確認兩個物件的資料是否相同
        if (Object.ReferenceEquals(x, y)) return true;

        //確認兩個物件是否有任何資料為空值
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //這邊就依照個人需求比對各個屬性的值,以此範例來說也可以只比對uName或比對uName跟uAge
        return x.uId == y.uId 
            && x.uName == y.uName 
            && x.uAge == y.uAge;
    }

    public int GetHashCode(CompareModel e)
    {
        //確認物件是否為空值
        if (Object.ReferenceEquals(e, null)) return 0;

        //取得uId欄位的HashCode
        int uId = e.uId == null ? 0 : e.uId.GetHashCode();

        //取得uName欄位的HashCode
        int uName = e.uName == null ? 0 : e.uName.GetHashCode();

        //取得uAge欄位的HashCode
        int uAge = e.uAge == null ? 0 : e.uAge.GetHashCode();

        //計算HashCode,因為是XOR所以要全部都是1才會回傳1,否則都會回傳0
        return uId ^ uName ^ uAge;
    }
}

接著建立兩個LIST來測試比對結果

void Main()
{
	List<CompareModel> UsersA = new List<CompareModel>();
	UsersA.Add(new CompareModel{
		uId = 1,
		uName = "AAA",
		uAge = 20,
	});
	UsersA.Add(new CompareModel{
		uId = 2,
		uName = "BBB",
		uAge = 22,
	});
	UsersA.Add(new CompareModel{
		uId = 3,
		uName = "CCC",
		uAge = 26,
	});
	
	List<CompareModel> UsersB = new List<CompareModel>();
	UsersB.Add(new CompareModel{
		uId = 2,
		uName = "BBB",
		uAge = 22,
	});
	UsersB.Add(new CompareModel{
		uId = 4,
		uName = "DDD",
		uAge = 25,
	});
	UsersB.Add(new CompareModel{
		uId = 6,
		uName = "EEE",
		uAge = 27,
	});
	
	var diffList = UsersA.Except(UsersB,new DataComparer());
	foreach(var item in diffList){
		Console.WriteLine(item.uId + "-" + item.uName + "-" + item.uAge);
	}
}

比對結果