UnionBy 方法的使用

 

如下範例,
1、指定一元素當 key,而當 key 值相同時,則視為同一筆資料。
2、key 還可以一次指定多個。
3、當在比較時,被視為相同資料時,則以基底為準。

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
List<Person> list1 = new List<Person>{
new Person { Id = 1, Name = "John", Body = "fat" },
new Person { Id = 2, Name = "Alice", Body = "fat" }
};

List<Person> list2 = new List<Person>{
new Person { Id = 2, Name = "Alice", Body = "thin" },
new Person { Id = 3, Name = "Kate", Body = "thin" }
};

var result = list1.UnionBy(list2, p => p.Id);
foreach (var person in result)
{
Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Body: {person.Body}");
}
Console.WriteLine();
//output:
//Id: 1, Name: John, Body: fat
//Id: 2, Name: Alice, Body: fat
//Id: 3, Name: Kate, Body: thin

var result2 = list2.UnionBy(list1, p => p.Id);
foreach (var person in result2)
{
Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Body: {person.Body}");
}
Console.WriteLine();
//output:
//Id: 2, Name: Alice, Body: thin
//Id: 3, Name: Kate, Body: thin
//Id: 1, Name: John, Body: fat

var result3 = list1.UnionBy(list2, p => new { p.Id, p.Name });
foreach (var person in result3)
{
Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Body: {person.Body}");
}
Console.WriteLine();
//output:
//Id: 1, Name: John, Body: fat
//Id: 2, Name: Alice, Body: fat
//Id: 3, Name: Kate, Body: thin

var result4 = list1.UnionBy(list2, p => new { p.Id, p.Name, p.Body });
foreach (var person in result4)
{
Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Body: {person.Body}");
}
Console.WriteLine();
//output:
//Id: 1, Name: John, Body: fat
//Id: 2, Name: Alice, Body: fat
//Id: 2, Name: Alice, Body: thin
//Id: 3, Name: Kate, Body: thin

class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Body { get; set; }
}