使用 ArrayList 儲存字串時,需確保不重複新增。ArrayList.Contains 方法可快速判斷元素是否存在。
using System;
using System.Collections;
public class ArrayListUniqueDemo
{
public static void Main()
{
ArrayList list = new ArrayList();
AddToList(list, "Table1");
AddToList(list, "Table4");
AddToList(list, "Table1"); // 重複,不會新增
AddToList(list, "Table3");
AddToList(list, "Table2");
AddToList(list, "Table2"); // 重複,不會新增
Console.WriteLine("列表內容(無重複):");
foreach (string s in list)
Console.WriteLine(s);
}
private static void AddToList(ArrayList list, string item)
{
if (!list.Contains(item))
list.Add(item);
}
}
列表內容(無重複):
Table1
Table4
Table3
Table2
List<string>:型別安全、效能更好、支援 LINQ。HashSet<string>(O(1) 查找)或 LINQ .Distinct()。var set = new HashSet { "Table1", "Table4", "Table1", "Table3", "Table2", "Table2" };
// 或
var list = new List { "Table1", "Table4", "Table1", "Table3", "Table2", "Table2" }
.Distinct()
.ToList();
| 集合類型 | Contains 效能 | 適用場景 |
|---|---|---|
ArrayList | O(n) 線性搜尋 | 舊版 .NET 1.x 專案維護 |
List<T> | O(n) 線性搜尋 | 一般清單,配合 .Distinct() |
HashSet<T> | O(1) 雜湊查找 | 高頻去重、大量資料 |