移除 List<T> 中的重複元素,保留唯一值。
using System.Linq;
List<int> list = new List<int> { 1, 2, 2, 3, 1, 4 };
List<int> unique = list.Distinct().ToList(); // [1, 2, 3, 4]
// 若需原地修改
list = list.Distinct().ToList();
Set,平均 O(n)。List<int> unique = new HashSet<int>(list).ToList(); // 順序可能改變
// .NET 6+ 可用
List<int> unique = list.ToHashSet().ToList();
for (int i = 0; i < list.Count; i++) {
for (int j = list.Count - 1; j > i; j--) {
if (list[i] == list[j]) list.RemoveAt(j);
}
}
// 注意:RemoveAt 會導致後續元素前移,倒序遍歷避免索引錯位
class Person { public int Id; public string Name; }
var uniquePeople = people
.GroupBy(p => p.Id)
.Select(g => g.First())
.ToList(); // 依 Id 去重,保留首筆
| 方法 | 耗時 | 記憶體 | 順序 |
|---|---|---|---|
| Distinct() | ~45 ms | ~16 MB | 保留 |
| HashSet 建構子 | ~30 ms | ~16 MB | 不保證 |
| 雙重迴圈 | ~12 秒 | ~0 MB | 保留 |
list.Distinct().ToList()** 最佳平衡。new HashSet(list).ToList()**。GroupBy(key).Select(g=>g.First())。