萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# LINQ 計算列表中元素出現次數:擴充方法一行搞定

擴充方法實作

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 命名空間。

copyright © 萬盛學電腦網 all rights reserved