ZetCode

C# List Count

最后修改日期:2025 年 5 月 4 日

本文提供了在 C# 列表中计算元素的指南,解释了有效实现此目的的不同方法。

在 C# 中,List 是一个动态集合,用于存储相同类型的元素。每个元素都有索引,允许通过其在列表中的位置直接访问。与数组不同,列表在大小上具有灵活性,使其适用于各种数据管理场景。

要确定列表中的元素数量,我们可以使用两种方法

这两种方法都提供了检索列表大小的有效方法,具体取决于用例以及是否需要过滤。

C# List Count 简单示例

在此示例中,我们演示了在 C# 列表中计算元素的两种方法——Count 属性和 Count() LINQ 扩展方法。

Program.cs
List<string> words = [ "sky", "cup", "new", "war", "wrong",
    "crypto", "forest", "water" ];

Console.WriteLine($"There are {words.Count} elements in the list");
Console.WriteLine($"There are {words.Count()} elements in the list");

两行都输出列表中的元素总数。Count 属性提供对元素计数的直接访问,而 LINQ 中的 Count() 在应用过滤条件时很有用。

$ dotnet run
There are 8 elements in the list
There are 8 elements in the list

C# List Count 与谓词

谓词是一个返回布尔值的函数。在下一个示例中,我们计算满足给定谓词的元素的数量。

Program.cs
List<string> words = [ "sky", "cup", "new", "war", "wrong",
    "crypto", "forest", "water" ];

var n = words.Where(e => e.StartsWith('w')).Count();
Console.WriteLine($"{n} words start with w");

var n2 = words.Count(e => e.StartsWith('c'));
Console.WriteLine($"{n2} words start with c");

该程序计算以“w”和“c”开头的单词的数量。

var n = words.Where(e => e.StartsWith('w')).Count();

在第一种情况下,我们使用 Where 方法过滤列表,然后在结果上调用 Count

var n2 = words.Count(e => e.StartsWith(;c;));

或者,我们可以将 lambda 表达式作为参数传递给 Count

$ dotnet run
3 words start with w
2 words start with c

C# List Count 与查询表达式

在下一个程序中,我们使用 LINQ 的查询表达式来计算元素。

Program.cs
List<Car> cars =
[
    new ("Audi", 52642),
    new ("Mercedes", 57127),
    new ("Skoda", 9000),
    new ("Volvo", 29000),
    new ("Bentley", 350000),
    new ("Citroen", 21000),
    new ("Hummer", 41400),
    new ("Volkswagen", 21600)
];

var n = (from car in cars
          where car.Price > 30000 && car.Price < 100000
          select car).Count();

Console.WriteLine(n);

record Car(string Name, int Price);

在该程序中,我们找出所有价格在 30000 到 100000 之间的汽车,并计算它们的数量。

$ dotnet run
3

C# List Count 分组

在此示例中,我们使用 LINQ 根据 C# 列表中元素的共同属性对它们进行分组,并计算每个组中的项目数。

该程序定义了一个汽车列表,每辆汽车都由名称、颜色和价格表示。汽车按颜色分组,每组中汽车的总数使用 Count 方法确定。

Program.cs
List<Car> cars =
[
    new ("Audi", "red", 52642),
    new ("Mercedes", "blue", 57127),
    new ("Skoda", "black", 9000),
    new ("Volvo", "red", 29000),
    new ("Bentley", "yellow", 350000),
    new ("Citroen", "white", 21000),
    new ("Hummer", "black", 41400),
    new ("Volkswagen", "white", 21600),
];

var groups = from car in cars
             group car by car.Colour into g
             select new { g.Key, Count = g.Count() };

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key}: {group.Count}");
}

record Car(string Name, string Colour, int Price);

每种独特的颜色都用作分组键,Count 方法检索每个类别中的汽车数量。这种技术对于总结分类数据和高效执行聚合任务特别有用。

$ dotnet run
red: 2
blue: 1
black: 2
yellow: 1
white: 2

来源

List Count 属性

在本文中,我们展示了如何在 C# 中计算列表元素。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我已经撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 C# 教程