Distinct() 與 DistinctBy() 的使用

 

Distinct() 與 DistinctBy() 的用法差別如下

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
List<TheRecord> list = new();
list.Add(new TheRecord() { Name = "Bob", Age = 30 });
list.Add(new TheRecord() { Name = "Bob", Age = 30 });
list.Add(new TheRecord() { Name = "Mary", Age = 30 });
list.Add(new TheRecord() { Name = "Mary", Age = 60 });

var r1 = list.Distinct().ToList();
// result:
// { Name = "Bob", Age = 30 }
// { Name = "Bob", Age = 30 }
// { Name = "Mary", Age = 30 }
// { Name = "Mary", Age = 60 }

var r2 = list.DistinctBy(x => x.Name).ToList();
// result:
// { Name = "Bob", Age = 30 }
// { Name = "Mary", Age = 30 }

var r3 = list.DistinctBy(x => new { x.Name, x.Age }).ToList();
// result:
// { Name = "Bob", Age = 30 }
// { Name = "Mary", Age = 30 }
// { Name = "Mary", Age = 60 }

List<string> s = new();
s.Add("a1");
s.Add("a1");
var r4 = s.Distinct().ToList();
// result:
// { "a1" }

public class TheRecord
{
public string Name { get; set; }
public int Age { get; set; }
}