C# Distinct List of Object

今日在Code Review 同事的 Code 時候發現了一個有趣的寫法
他想做的是 Return 一個Distinct 左既 List Of Object

好直接既想法是使用 Distinct

List.Distinct();

之後發現 Distinct 是不能 Distinct Object 的
同事的寫法是用了 List 加 GroupBySelect First()

List.GrounBy(x =>; x.key).Select(x => x.First());

之後發現.. 原來我們可以使用 GroupByFirst 來做到 Distinct Object 的效果
以下是我的 Code Sample

void Main()
{
	var list = new List<Example>();
	list.Add(new Example() {Id=1, Name="Example 1", Comment="Comment 1" });
	list.Add(new Example() {Id=1, Name="Example 1", Comment="Comment 1" });
	list.Add(new Example() {Id=1, Name="ExamplE 1", Comment="Comment 2" });
	list.Add(new Example() {Id=2, Name="Example 2", Comment="Comment 3" });
	list.Add(new Example() { Id = 2, Name = "example 2", Comment = "Comment 3" });
	list.Add(new Example() { Id = 3, Name = "Example 3", Comment = "Comment 3" });
	list.Add(new Example() { Id = 4, Name = "Example 4", Comment = "Comment 3" });
	list.Add(new Example() { Id = 5, Name = "Example 5", Comment = "Comment 3" });

	Console.WriteLine("Use List.Distinct()");
	list.Distinct().Dump();

	Console.WriteLine("Use Group By Fields");
	list.GroupBy(x => new {x.Id, Name=x.Name}).Select(x =>x.First()).Dump();

	Console.WriteLine("Use Group By and make it ignore case");
	list.GroupBy(x => new {x.Id, Name=x.Name.ToLower()}).Select(x =>x.First()).Dump();
}

public class Example
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string Comment {get;set;}
}

Output:

Hope you find it useful

Chi Yau
Chi Yau
Software Engineer

Interested on Learning new stuff and experience sharing