C# filter list
last modified December 3, 2021
C# filter list tutorial shows how to filter a list in C#. C# tutorial is a comprehensive tutorial on C# language.
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.
The example filters out all words that have three characters.
var words = new List { "sky", "rock", "forest", "new", "falcon", "jewelry" };We have a list of words. The goal is to find out all words with three letters.
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,newC# filter list with FindAll
In the following example, we filter a list with the built-in FindAll method.
The example finds out all integer values that are greater than zero.
List filtered = vals.FindAll[e => e > 0];The FindAll method retrieves all the elements that match the conditions defined by the specified predicate.
C# filter list with LINQ query expression
The following example uses a LINQ query expression to filter a list.
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.
The example filters out all positive values.
List 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.
The example selects all cars whose price is between 9000 and 50000.
$ dotnet run Volvo 29000 Citroen 21000 Hummer 41400 Volkswagen 21600C# filter an array with Func
In the example, we use a Func delegate to filter an array of users.
From the array of users, we get those that live in Bratislava.
var city = "Bratislava"; Func 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 }In this tutorial, we have showed how to filter a list in C#.
Read C# tutorial or list all C# tutorials.