One of the fundamental methods provided by LINQ is the Where
filtering method, which allows developers to filter data based on specified conditions. In this article, we will discuss on LINQ’s Where
method and explore its various applications in C#.
What is Filtering?
Filtering is nothing but the process to get only those elements from a data source that satisfied the given condition. It is also possible to fetch the data from a data source with more than one condition as per our business requirements. For example:
- Employees having a salary greater than 50000.
- Students Having Marks greater than 80% from a particular batch.
- Employees having experience of more than 6 Years and the department is IT, etc.
The “Where” Method always expects at least one condition and we can specify the condition(s) using predicates. The conditions can be written using the ==, >=, <=, &&, ||, >, <, etc. symbols.
What is a Predicate in C#?
A Predicate is nothing but a function or technically you can say a delegate that is used to test each and every element for a given condition. In the below example, the Lambda expression (num => num > 5) runs for each and every element present in the “intList” collection. Then it will check, whether the number is greater than 5, then a boolean value true is returned otherwise false. In the below example, I am showing both Method and Query Syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
static void Main(string[] args) { List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Method Syntax IEnumerable<int> filteredData = intList.Where(num => num > 5); //Query Syntax IEnumerable<int> filteredResult = from num in intList where num > 5 select num; foreach (int number in filteredData) { Console.WriteLine(number); } Console.ReadKey(); } |
Second Overloaded Version of the Where Method in LINQ
In the second overloaded version of the “Where” extension method, the int parameter of the predicate function represents the index position of the source element.
1 2 3 4 5 |
public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate); |
Let us see an example to understand this. Here we need to filter only the odd numbers i.e. the numbers which are not divisible by 2. Along with the numbers we also need to fetch the index position of the number. The index is 0 based.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
static void Main(string[] args) { List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Method Syntax var OddNumbersWithIndexPosition = intList.Select((num, index) => new { Numbers = num, IndexPosition = index }).Where(x => x.Numbers % 2 != 0) .Select(data => new { Number = data.Numbers, IndexPosition = data.IndexPosition }); foreach (var item in OddNumbersWithIndexPosition) { Console.WriteLine($"IndexPosition :{item.IndexPosition} , Value : {item.Number}"); } Console.ReadKey(); } |
Now run the application and you will see the odd numbers along with their index position as shown below.
Rewrite the same example using Query Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
static void Main(string[] args) { List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Query Syntax var OddNumbersWithIndexPosition = from number in intList.Select((num, index) => new {Numbers = num, IndexPosition = index }) where number.Numbers % 2 != 0 select new { Number = number.Numbers, IndexPosition = number.IndexPosition }; foreach (var item in OddNumbersWithIndexPosition) { Console.WriteLine($"IndexPosition :{item.IndexPosition} , Value : {item.Number}"); } Console.ReadKey(); } |
Now run the application and it will also give the same output as the method syntax output as shown in the below image.
Complex Example for LINQ Where Extension
Let us see how to use the LINQ Where Extension Method with Complex Data Type using C#. We are going to use the following Employee class. So, create a class file with the name Employee.cs and then copy and paste the following code into it. As we can see. we created the following Employee class with five properties i.e. ID, Name, Gender, Salary, and Technology. Here, we have also created one method which will return the list of all employees which will be going to our data source.
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 |
public class Employee { public int ID { get; set; } public string Name { get; set; } public string Gender { get; set; } public int Salary { get; set; } public List<string> Technology { get; set; } public static List<Employee> GetEmployees() { List<Employee> employees = new List<Employee>() { new Employee {ID = 101, Name = "Preety", Gender = "Female", Salary = 60000, Technology = new List<string>() {"C#", "Jave", "C++"} }, new Employee {ID = 102, Name = "Priyanka", Gender = "Female", Salary = 50000, Technology =new List<string>() { "WCF", "SQL Server", "C#" } }, new Employee {ID = 103, Name = "Hina", Gender = "Female", Salary = 40000, Technology =new List<string>() { "MVC", "Jave", "LINQ"}}, new Employee {ID = 104, Name = "Anurag", Gender = "Male", Salary = 450000}, new Employee {ID = 105, Name = "Sambit", Gender = "Male", Salary = 550000}, new Employee {ID = 106, Name = "Sushanta", Gender = "Male", Salary = 700000, Technology =new List<string>() { "ADO.NET", "C#", "LINQ" }} }; return employees; } } |
Now, we need to fetch all the employees whose salary is greater than 50000. For this, we need to use the LINQ Where Extension Method and we need to specify the condition as emp => emp.Salary > 50000 using Method Syntax and employee.Salary > 50000 using Query Syntax which is shown in the below example.
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 |
static void Main(string[] args) { //Query Syntax var QuerySyntax = from employee in Employee.GetEmployees() where employee.Salary > 50000 select employee; //Method Syntax var MethodSyntax = Employee.GetEmployees() .Where(emp => emp.Salary > 50000); foreach (var emp in QuerySyntax) { Console.WriteLine($"Name : {emp.Name}, Salary : {emp.Salary}, Gender : {emp.Gender}"); if(emp.Technology != null && emp.Technology.Count() > 0) { Console.Write(" Technology : "); foreach (var tech in emp.Technology) { Console.Write(tech + " "); } Console.WriteLine(); } else { Console.WriteLine(" Technology Not Available "); } } Console.ReadKey(); } |
Multiple Conditions using LINQ Where Method
We need to fetch all the employees whose gender is Male and also whose Salary is greater than 500000. So, here we have two conditions. The first condition is Gender = Male and the second condition is Salary > 500000. If we have more than one condition, then we need to use && (AND) or || (OR) logical Operators based on our requirement. Here, we are going to use the AND (&&). That means if both the conditions satisfy then only return the data.
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 |
static void Main(string[] args) { //Query Syntax var QuerySyntax = from employee in Employee.GetEmployees() where employee.Salary > 500000 && employee.Gender == "Male" select employee; //Method Syntax var MethodSyntax = Employee.GetEmployees() .Where(emp => emp.Salary > 500000 && emp.Gender == "Male") .ToList(); foreach (var emp in MethodSyntax) { Console.WriteLine($"Name : {emp.Name}, Salary : {emp.Salary}, Gender : {emp.Gender}"); if(emp.Technology != null && emp.Technology.Count() > 0) { Console.Write(" Technology : "); foreach (var tech in emp.Technology) { Console.Write(tech + " "); } Console.WriteLine(); } else { Console.WriteLine(" Technology Not Available "); } } Console.ReadKey(); } |
Complex Example to Understand LINQ Where Method
Let us see a more complex example to understand the LINQ Where Extension Method. Now, we are going to provide Multiple conditions with the custom operations and project the data to an anonymous type. The following is our business requirement.
We need to fetch all the employees whose salary is greater than or equal to 50000 and technology should not be null. And we need to project the following information to an anonymous type.
- Name as it is
- Gender as it is
- MonthlySalary = Salary / 12
The Complete Example Code is Given Below. In the below example, I am showing both the Method and Query syntax with the Where Extension Method to achieve the above requirement.
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 |
static void Main(string[] args) { //Query Syntax var QuerySyntax = (from employee in Employee.GetEmployees() where employee.Salary >= 50000 && employee.Technology != null select new { EmployeeName = employee.Name, Gender = employee.Gender, MonthlySalary = employee.Salary / 12 }).ToList(); //Method Syntax var MethodSyntax = Employee.GetEmployees() .Where(emp => emp.Salary >= 50000 && emp.Technology != null) .Select(emp => new { EmployeeName = emp.Name, Gender = emp.Gender, MonthlySalary = emp.Salary / 12 }) .ToList(); foreach (var emp in QuerySyntax) { Console.WriteLine($"Name : {emp.EmployeeName}, Gender : {emp.Gender}, Monthly Salary : {emp.MonthlySalary}"); } Console.ReadKey(); } |
Index position using Where Method in C#
Now, we need to fetch all the employees whose Gender is Male and whose Salary is greater than 500000 along with their index position to an anonymous type.
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 |
static void Main(string[] args) { //Query Syntax var QuerySyntax = (from data in Employee.GetEmployees().Select((Data, index) => new { employee = Data, Index = index }) where data.employee.Salary >= 500000 && data.employee.Gender == "Male" select new { EmployeeName = data.employee.Name, Gender = data.employee.Gender, Salary = data.employee.Salary, IndexPosition = data.Index }).ToList(); //Method Syntax var MethodSyntax = Employee.GetEmployees().Select((Data, index) => new { employee = Data, Index = index }) .Where(emp => emp.employee.Salary >= 500000 && emp.employee.Gender == "Male") .Select(emp => new { EmployeeName = emp.employee.Name, Gender = emp.employee.Gender, Salary = emp.employee.Salary, IndexPosition = emp.Index }) .ToList(); foreach (var emp in QuerySyntax) { Console.WriteLine($"Position : {emp.IndexPosition} Name : {emp.EmployeeName}, Gender : {emp.Gender}, Salary : {emp.Salary}"); } Console.ReadKey(); } |
The Where
method in LINQ is a powerful tool for filtering data in C#. It allows developers to easily define and apply conditions on collections, resulting in concise and readable code. By leveraging the expressive syntax of lambda expressions, C# programmers can filter and extract precisely the data they need from a variety of data sources. Understanding the Where
method and
Leave a Comment