首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# List 去除重複值:Distinct、HashSet 與雙重迴圈效能比較

     編輯:程式設計疑難解答

需求

移除 List<T> 中的重複元素,保留唯一值。

方案一:LINQ Distinct(最簡潔、推薦)

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)。

方案二:HashSet 建構子(效能最佳、不保證順序)

List<int> unique = new HashSet<int>(list).ToList(); // 順序可能改變
// .NET 6+ 可用
List<int> unique = list.ToHashSet().ToList();

方案三:手動雙重迴圈(教學用、O(n²))

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 去重,保留首筆

效能測試(100 萬筆 int,.NET 8,Release)

方法耗時記憶體順序
Distinct()~45 ms~16 MB保留
HashSet 建構子~30 ms~16 MB不保證
雙重迴圈~12 秒~0 MB保留

總結建議

  1. 一般情況:**list.Distinct().ToList()** 最佳平衡。
  2. 極致效能且不在乎順序:**new HashSet(list).ToList()**。
  3. 複雜物件去重:GroupBy(key).Select(g=>g.First())。
  4. 避免手寫雙重迴圈,除非嵌入式極度受限環境。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved