ZetCode

C# 过滤列表

最后修改于 2025 年 6 月 8 日

在本文中,我们将探讨在 C# 中过滤列表的不同技术。 无论您是处理大型数据集还是优化搜索功能,理解高效的过滤方法都至关重要。

本教程涵盖了在 C# 中过滤列表的多种方法,包括迭代、LINQ 查询以及内置的 FindAllRemoveAll 方法。

使用迭代进行 C# 过滤列表

在第一个示例中,我们使用 foreach 循环来过滤列表。

Program.cs
List<string> words = [ "sky", "rock", "forest", "new",
    "falcon", "jewelry" ];

List<string> filtered = [];

foreach (var word in words)
{
    if (word.Length == 3)
    {
        filtered.Add(word);
    }
}

Console.WriteLine(string.Join(',', filtered));

该示例过滤掉所有包含三个字符的单词。

List<string> words = [ "sky", "rock", "forest", "new",
    "falcon", "jewelry" ];

我们有一个单词列表。 目标是找出所有包含三个字母的单词。

List<string> filtered = [];

创建一个新的 filtered 列表。 所有符合条件的单词都将被添加到该列表中。

foreach (var word in words)
{
    if (word.Length == 3)
    {
        filtered.Add(word);
    }
}

我们使用 foreach 循环遍历单词列表。 所有符合 if 条件的单词都将被添加到 filtered 列表中。

Console.WriteLine(string.Join(',', filtered));

我们将 filtered 列表的内容显示到控制台。

$ dotnet run
sky,new

使用 FindAll 进行 C# 过滤列表

在以下示例中,我们使用内置的 FindAll 方法来过滤列表。

Program.cs
List<int> vals = [-1, -3, 0, 1, 3, 2, 9, -4];
List<int> filtered = vals.FindAll(e => e > 0);

Console.WriteLine(string.Join(',', filtered));

该示例找出所有大于零的整数值。

List<int> filtered = vals.FindAll(e => e > 0);

FindAll 方法检索所有符合指定谓词定义的条件的元素。

$ dotnet run
1,3,2,9

使用 LINQ 查询表达式进行 C# 过滤列表

以下示例使用 LINQ 查询表达式来过滤列表。

Program.cs
List<string> words = [ "sky", "rock", "forest", "new",
        "falcon", "jewelry" ];

var query = from word in words
            where word.Length == 3
            select word;

foreach (var word in query)
{
    Console.WriteLine(word);
}

该示例选择所有包含三个字符的单词。 where 子句根据指定的条件过滤单词,而 select 子句指定要返回的元素。

使用 LINQ Where 进行 C# 过滤列表

下一个示例使用 LINQ 的 Where 方法来过滤列表。 与使用 foreach 循环或 FindAll 方法相比,这是一种更简洁的过滤集合的方法。 它采用一个谓词函数来定义过滤条件,并返回一个仅包含满足该条件的元素的新列表。

Program.cs
List<int> vals = [-1, -3, 0, 1, 3, 2, 9, -4];
List<int> filtered = vals.Where(x => x > 0).ToList();

Console.WriteLine(string.Join(',', filtered));

该示例过滤掉所有正值。

List<int> filtered = vals.Where(x => x > 0).ToList();

Where 方法基于谓词过滤一系列值。

C# 过滤对象列表

在以下示例中,我们使用 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", 21601)
];

foreach (var car in from car in cars
                    where car.Price > 9000 && car.Price < 50000
                    select new { car.Name, car.Price })
{
    Console.WriteLine($"{car.Name} {car.Price}");
}

record Car(string Name, int Price);

该示例选择所有价格在 9000 到 50000 之间的汽车。

$ dotnet run
Volvo 29000
Citroen 21000
Hummer 41400
Volkswagen 21600

使用 Func 进行 C# 过滤列表

在此示例中,我们使用 Func 委托来过滤用户列表。 这种方法允许我们定义一个谓词函数,该函数可以重用,以便根据不同的条件进行过滤。 Func 委托表示一个接受单个参数并返回布尔值的方法,使其适合与 LINQ 方法(如 Where)一起使用。

Program.cs
List<User> users =
[
    new (1, "John", "London", "2001-04-01"),
    new (2, "Lenny", "New York", "1997-12-11"),
    new (3, "Andrew", "Boston", "1987-02-22"),
    new (4, "Peter", "Prague", "1936-03-24"),
    new (5, "Anna", "Bratislava", "1973-11-18"),
    new (6, "Albert", "Bratislava", "1940-12-11"),
    new (7, "Adam", "Trnava", "1983-12-01"),
    new (8, "Robert", "Bratislava", "1935-05-15"),
    new (9, "Robert", "Prague", "1998-03-14"),
];

var city = "Bratislava";
Func<User, bool> livesIn = e => e.City == city;

var res = users.Where(livesIn);

foreach (var e in res)
{
    Console.WriteLine(e);
}

record User(int Id, string Name, string City, string DateOfBirth);

从用户数组中,我们获取那些居住在布拉迪斯拉发的用户。

var city = "Bratislava";
Func<User, bool> livesIn = e => e.City == city;

在谓词中,一个返回布尔值的函数,我们测试所有 City 属性等于 city 变量的用户对象。

var res = users.Where(livesIn);

我们将 livesIn 谓词传递给 Where 方法。

$ dotnet run
User { Id = 5, Name = Anna, City = Bratislava, DateOfBirth = 1973-11-18 }
User { Id = 6, Name = Albert, City = Bratislava, DateOfBirth = 1940-12-11 }
User { Id = 8, Name = Robert, City = Bratislava, DateOfBirth = 1935-05-15 }

使用 RemoveAll 进行 C# 过滤列表

RemoveAll 方法从列表中删除所有符合指定谓词定义的条件的元素。 此方法就地修改原始列表。

Program.cs
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

numbers.RemoveAll(n => n % 2 == 0);
Console.WriteLine(string.Join(",", numbers));

在此示例中,所有偶数都从列表中删除。 RemoveAll 方法接受一个谓词并删除所有满足该条件的元素。

$ dotnet run
1,3,5,7,9

来源

筛选数据

在本文中,我们学习了如何使用各种技术(如迭代、FindAll 方法、RemoveAll 方法、LINQ 查询表达式和 Where 方法)在 C# 中过滤列表。 每种方法都有其自身的优点和用例,允许开发人员为他们的特定需求选择最合适的方法。 无论您喜欢迭代的简单性、内置方法的便利性还是 LINQ 的强大功能,C# 都提供了灵活的选项来有效地过滤列表。

作者

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

列出所有 C# 教程