ภาพรวม
ใช้ LINQ Distinct() สร้าง List ใหม่ที่ไม่มีค่าซ้ำ รักษาลำดับการปรากฏครั้งแรก
โค้ดตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List<int> list = new List<int> { 50, 90, 50, 100 };
Console.WriteLine("Initial List:");
list.ForEach(x => Console.WriteLine(x));
// ลบซ้ำ
List<int> uniqueList = list.Distinct().ToList();
Console.WriteLine("\nAfter removing duplicates:");
uniqueList.ForEach(x => Console.WriteLine(x));
}
}
ผลลัพธ์
Initial List:
50
90
50
100
After removing duplicates:
50
90
100
วิธีอื่นๆ
1. HashSet (ไม่รักษาลำดับ, เร็วกว่า)
var uniqueSet = new HashSet<int>(list);
var uniqueList = uniqueSet.ToList(); // ลำดับไม่แน่นอน
2. In-place Removal (แก้ไข List เดิม - O(n²) ช้า)
// ไม่แนะนำสำหรับ List ใหญ่
for (int i = list.Count - 1; i >= 0; i--) {
if (list.IndexOf(list[i]) != i) {
list.RemoveAt(i);
}
}
3. ใช้ Dictionary/HashSet Track Manually (O(n), รักษาลำดับ)
var seen = new HashSet<int>();
var unique = new List<int>();
foreach (int item in list) {
if (seen.Add(item)) { // Add คืนค่า true ถ้าเพิ่มใหม่ (ยังไม่เคยมี)
unique.Add(item);
}
}
// unique = [50, 90, 100] - รักษาลำดับ, O(n)
4. สำหรับ Object ต้องใช้ IEqualityComparer
public class Item {
public int Id { get; set; }
public string Name { get; set; }
}
var items = new List<Item> { ... };
var uniqueItems = items.Distinct(new ItemComparer()).ToList();
public class ItemComparer : IEqualityComparer<Item> {
public bool Equals(Item x, Item y) => x?.Id == y?.Id;
public int GetHashCode(Item obj) => obj?.Id.GetHashCode() ?? 0;
}
Performance Comparison
| Method | Time | Space | Preserves Order |
|---|---|---|---|
| Distinct() | O(n) | O(n) | Yes |
| HashSet Constructor | O(n) | O(n) | No |
| Manual HashSet + List | O(n) | O(n) | Yes |
| In-place RemoveAt | O(n²) | O(1) | Yes |