透過 LINQ 查詢語法,可輕鬆實作泛型擴充方法計算特定元素在 List<T> 中出現的次數:
public static int CountTimes<T>(this List<T> inputList, T searchItem)
{
return (from t in inputList where t.Equals(searchItem) select t).Count();
}
var list = new List<string> { "apple", "banana", "apple", "cherry" };
int count = list.CountTimes("apple"); // 回傳 2
此方法語意清晰、類似 SQL 語法,適用於任何實作 Equals 的型別。