Filter a List in C#
This post will discuss how to filter a list in C#.
1. Using Enumerable.Where() Method
A simple and elegant solution to filter a list is using LINQ. It has a Where() method that filters a sequence of values based on the specified predicate. The following code example demonstrates how we can use Where() for filtering a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 }; List<int> odd = list.Where(x => x % 2 == 1).ToList(); Console.WriteLine(String.Join(", ", odd)); // 1, 3, 5, 7 } } |
Note that the above solution allocates a new list. The following code example uses the Where() clause to filter a sequence of objects by their age.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Linq; using System.Collections.Generic; public class Person { public string name { get; set; } public int age { get; set; } public Person(string name, int age) { this.name = name; this.age = age; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { List<Person> list = new List<Person> { new Person("x", 27), new Person("y", 20), new Person("z", 24), new Person("z", 30) }; List<Person> filteredList = list.Where(item => item.age > 25).ToList(); Console.WriteLine(String.Join(", ", filteredList)); } } |
2. Using List<T>.FindAll() Method
The List<T>.FindAll() method retrieves all elements of the list that matches with the specified predicate delegate. We can use it as follows to filter a list in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 }; List<int> odd = list.FindAll(x => x % 2 == 1).ToList(); Console.WriteLine(String.Join(", ", odd)); // 1, 3, 5, 7 } } |
That’s all about filtering a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)