差集運算

差集運算指的是兩份清單中,不一樣的部分;依照A差集B,或是B差集A,會有不同的結果

忘了在哪邊看到的,大概就是【我有的你沒有】這樣的概念,朗朗上口挺好記

這邊可以看一下WIKI上面的圖可能會比較好理解一點

1
2
3
4
5
 	var list1 = new[] { 1, 2, 3, 4, 5 };
var list2 = new[] { 4, 5, 6, 7, 8 };

var array = list1.Except(list2).ToArray();
var result = string.Join(",", array); // 1,2,3

但是如果今天要比較計算的是物件,就不能直接用Except來做了,需要告訴程式怎麼樣去比較物件,透過繼承IEqualityComparer來實作比較的方法,下面是LINQPAD的範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
void Main()
{
var list1 = new List<User>
{
new User {Name = "AAA", Age = 20},
new User {Name = "BBB", Age = 20},
new User {Name = "CCC", Age = 20},
new User {Name = "DDD", Age = 20},
new User {Name = "EEE", Age = 20},
};
var list2 = new List<User>
{
new User {Name = "DDD", Age = 20},
new User {Name = "EEE", Age = 20},
new User {Name = "FFF", Age = 20},
};

var result = list1.Except(list2, new UserEqualityComparer()).ToList();
result.Dump();
}

// Define other methods and classes here
class UserEqualityComparer : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
return x.Name == y.Name && x.Age == y.Age;
}

public int GetHashCode(User obj)
{
var name = obj.Name == null ? 0 : obj.Name.GetHashCode();
var age = obj.Age.GetHashCode();
return name ^ age;
}
}
class User
{
public string Name { get; set; }
public int Age { get; set; }
}