Three options to filter a list in C#
Orsan Awawdi
Software Engineer | Extensive experience in automation using Python and Jenkins
I will show here three different ways to filter text by some string criteria in C#.
We have a public class called "Student" which holds Students' names.
Every new object of Students is inserted into a list called ListOfStudents as follows.
I also added ListBox control which is bound to ListOfStudents, in order to display the results.
static List<Students> ListOfStudents = new List<Students>();
Students newStudentObj = new Students(txtAddStudent.Text);
ListOfStudents.Add(newStudentObj);
Now, in order to search the name of the student according to some text entered by the user, I can use a simple "Filter" method.
var searchResult = Filter(ListOfStudents, txtSearch.Text);
This method take the Students list as a first argument and the text to search as a second argument. Simple.
The second option is to create a Filter method as an Extension Method. This will allow me to call the filter method like this:
var searchResult = ListOfStudents.Filter(txtSearch.Text);
In order to accomplish this, I need to create a new static class inside the same namespace, let's call it 'SearchStudentByName', inside this class I will create a static Filter method which takes my Students list as a first argument, and the text to search as a second argument. The first argument is preceded by 'this' keyword, in order to extend the functionality of the method, and from now on every single instance of List of Students can use it.
In addition I added a foreach to loop my list of students and return the result. Here is the implementation:
I can take this one more step forward, and use the third option. I will use #LINQ to accomplish this. LINQ is a C# library that enables query capabilities directly into the C# language, and can be used by adding System.Linq namespace.
I will use the LINQ's special Where method to loop the list of Students using 'x' iterator, and return the results that contains the text I am looking for as a list. Simple yet powerful.