Filter a List in C#

In C#, there are several ways to filter a list depending on the requirements and the type of list being used. Following are some of the possible ways to filter a list in C#:

Using the Where method

You can filter a list using the Where method which is available as an extension method in the System.Linq namespace.

Following is an example of how to use Where to filter a list of integers:

using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 }; IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0); foreach (int num in evenNumbers) { Console.WriteLine(num); } } }
//Output: 2 4

In the above code, first create a list of integers called numbers. Then use the Where method to filter the list to only include even numbers, using a lambda expression as the parameter to the Where method. The lambda expression checks if each element in the list is even by using the modulo operator %. Finally, iterate over the filtered list and print each element to the console.

You can customize the filter condition in the lambda expression based on your specific requirements.

Using LINQ Query

One of the most common ways to filter a list in C# is by using LINQ (Language-Integrated Query) queries. The following code shows how to filter a list of integers using a LINQ query:

List<int> numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Filter the even numbers from the list var evenNumbers = from num in numbers where num % 2 == 0 select num; // Display the filtered numbers foreach (var num in evenNumbers) { Console.WriteLine(num); }
//Output: 2 4 6 8 10

Using the FindAll method

The List class in C# provides a FindAll method that can be used to filter a list. The following code shows how to filter a list of doubles using the FindAll method:

List<double> prices = new List<double>{ 10.5, 15.75, 20.00, 12.25, 18.50 }; // Filter the prices that are greater than 15 var filteredPrices = prices.FindAll(price => price > 15); // Display the filtered prices foreach (var price in filteredPrices) { Console.WriteLine(price); }
//Output: 15.75 20.00 18.50

Above are some of the possible ways to filter a list in C#. Choose the one that best suits your needs and the type of list being used.

C# List

C# List is a collection of objects that can be dynamically resized as needed. It is similar to an array, but provides more flexibility in terms of adding, removing, and inserting elements at any position within the list. The List class is part of the System.Collections.Generic namespace and is widely used in C# programming.