ZetCode

C# filter list

last modified January 19, 2024

In this article we show how to filter a list in C#.

This tutorial shows several ways to filter a list in C# language. We use iteration, LINQ, and built-in FindAll method.

C# filter list with iteration

In the first example, we use a foreach loop to filter a list.

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));

The example filters out all words that have three characters.

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

We have a list of words. The goal is to find out all words with three letters.

List<string> filtered = [];

A new filtered list is created. All the words that match the condition will be added to the list.

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

We go over the list of words in a foreach loop. All words that match the if condition are added to the filtered list.

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

We show the contents of the filtered list to the console.

$ dotnet run
sky,new

C# filter list with FindAll

In the following example, we filter a list with the built-in FindAll method.

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));

The example finds out all integer values that are greater than zero.

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

The FindAll method retrieves all the elements that match the conditions defined by the specified predicate.

$ dotnet run
1,3,2,9

C# filter list with LINQ query expression

The following example uses a LINQ query expression to filter a list.

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);
}

The example selects all words that have three characters.

C# filter list with LINQ Where

The next example filters a list with LINQ's Where method.

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));

The example filters out all positive values.

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

The Where method filters a sequence of values based on a predicate.

C# filter a list of objects

In the following example we filter a list of car objects with a LINQ query expression.

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);

The example selects all cars whose price is between 9000 and 50000.

$ dotnet run
Volvo 29000
Citroen 21000
Hummer 41400
Volkswagen 21600

C# filter List with Func

In the example, we use a Func delegate to filter a list of users.

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);

From the array of users, we get those that live in Bratislava.

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

In the predicate, a function which returns a boolean value, we test all user objects whose City attribute is equal to the city variable.

var res = users.Where(livesIn);

We pass the livesIn predicate to the Where method.

$ 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 }

Source

Filtering data

In this article we have showed how to filter a list in C#.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.