In LINQ, Filtering operators are used to filter list/collection data based on filter conditions. In LINQ, we have two types of filtering operators those are
The following table shows more detail regarding filtering operators in LINQ.
Operator | Description | Query Syntax |
---|---|---|
Where | This operator is used to select values from the list based on predicate functions. | where |
OfType | This operator is used to select values based on their ability to caste a specified type. | Not Applicable |
A filtering operator in LINQ specifies the statement should only affect rows that meet specified criteria. The criteria expressed as predicates, the where clause is not a mandatory clause of LINQ statements but can be used to limit the number of records affected by a LINQ. The where clause is only used to extract records from select, delete, update,, etc.
Following is the syntax of using LINQ where clause filtering operator in method syntax to get data from collection list based on conditions.
C# Code
VB.NET Code
Let's see an example of using where clause filtering operator in LINQ.
Following is the example of using LINQ where clause filtering operator with method syntax to filter records based on where condition.
C# Code
VB.NET Code
Here we have used a filtering operator which is our Where Clause; in the program, we have an array string that has countries. Now we want to display those countries whose first letter starts with “A”.
To do this, we have used a where clause to specify a condition just like we do in normal SQL. Then we used a lambda expression to specify an input parameter x and use StartsWith function on the input parameter to denote that we want only those countries from the array whose name starts with “A”.
We will get output in the form of IEnumerable of type string and iterate through the collection to access the countries. Following is the result of using the Where clause in the method syntax example.
We can use a filtering operator where clause in query syntax to filter list/collection data based on conditions. Following is the syntax of defining where clause with query syntax.
C# Code
VB.NET Code
If you observe the above syntax, we used LINQ where clause in query syntax to get data from the list based on condition.
Following is the example of using LINQ where clause in query syntax to get data from the list based on conditions.
C# Code
VB.NET Code
If you observe the above code, we defined the required conditions using LINQ where clause.
Following is the result of using LINQ where clause in method syntax to filter data in the list based on where condition.
In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below.
C# Code
VB.NET Code
This is how we can use LINQ where clause filtering operator to filter data based on conditions.