using System;
using System.Collections.Generic;
using System.Linq;
public static class ListExtensions
{
///
/// 計算指定項目在列表中出現的次數
///
public static int CountTimes<T>(this List<T> list, T item)
{
if (list == null) throw new ArgumentNullException(nameof(list));
return list.Count(x => EqualityComparer<T>.Default.Equals(x, item));
}
}
var numbers = new List<int> { 1, 2, 3, 2, 4, 2, 5 };
int count = numbers.CountTimes(2); // 3
var words = new List<string> { "apple", "banana", "apple", "cherry" };
int count = words.CountTimes("apple"); // 2
list.Count(predicate) 是 LINQ 擴充方法,內部迴圈計算符合條件的元素數。EqualityComparer<T>.Default 自動處理 null、值型別、參考型別相等比較,比直接 x == item 更安全。O(n),空間 O(1)。var freq = numbers.GroupBy(x => x)
.ToDictionary(g => g.Key, g => g.Count());
// {1:1, 2:3, 3:1, 4:1, 5:1}
LINQ Count(predicate) 配合擴充方法,讓「計算出現次數」變成語意清晰的一行代碼。記得引用 System.Linq 命名空間。