C# Count:获取 ICollection中的元素数

  • Post category:C#

C#Count 的完整攻略

C#Count 是一个用于计算集合中指定元素个数的方法,它支持泛型集合(如 List、Dictionary 等)和数组。本攻略将从以下几个方面详细讲解如何使用 C#Count 方法。

语法

int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
  • source:需要计算元素个数的 IEnumerable 集合
  • predicate:一个用于测试每个元素是否满足条件的函数,返回 true 表示满足条件,false 表示不满足条件。

示例1:计算List中指定元素的数量

假设有一个 List 存储了一个班级每个学生的英语成绩,我们想要计算该班级及格(成绩大于等于60分)的学生人数。

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> scores = new List<int>() { 90, 85, 55, 75, 95 };
        int passedCount = scores.Count(score => score >= 60);
        Console.WriteLine($"The count of passed students is: {passedCount}");
    }
}

输出结果为:

The count of passed students is: 4

示例2:计算Dictionary中指定键值的数量

假设有一个 Dictionary 存储了一些品种的狗,我们想要计算该字典中黄色的狗的数量。

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, string> dogs = new Dictionary<string, string>();
        dogs.Add("GoldenRetriever", "Yellow");
        dogs.Add("Husky", "White");
        dogs.Add("LabradorRetriever", "Yellow");
        dogs.Add("Poodle", "Black");
        int count = dogs.Count(dog => dog.Value == "Yellow");
        Console.WriteLine($"The count of yellow dogs is: {count}");
    }
}

输出结果为:

The count of yellow dogs is: 2

结论

通过以上两个示例,我们可以看出 C#Count 方法能够快速便捷地计算集合中指定元素的数量,同时该方法也应用了 LINQ 的思想,可以方便地和其他 LINQ 方法结合使用,提高代码的可读性和简洁性。