Restriction Operator in LINQ

by Sachin Singh


Posted on Friday, 05 February 2021

Tags: Restriction Operator in LINQ Where operator in Linq OfType operator in Linq

In LINQ, Filtering/Restriction operators are used to filter a list or collection based on some conditions called a filter condition, here the collection can be of any type as a collection of integers, collection of a complex object, collection of strings, etc. LINQ provides us two types of filtering operators as shown below
    • Where
    • OfType

Following table shows more detail regarding filtering operators in LINQ.

Filtering Operators in LINQ
LINQ Filtering Operators

Where

Where operator is used to filter a collection based on a filter condition or better say a filter function. Like all other LINQ operators where() is an extension method on IEnumerable which simply means we can apply where() method with any collection which implements IEnumerable interface. In .Net every collection is inherited from IEnumerable so you can use Where() extension method to filter any type of collection. Now let's see the signature of Where() method.

Where Operator in LINQ
Where Operator in LINQ

As you can see in the diagram above Where() is an extension method which extends the IEnumerable and takes a Func delegate , we already know a Func is a generic delegate , being a delegate it can accept any method of same signature which means we can pass any method which returns a Boolean , as a parameter to Where() method , we also know that lambda expressions also serves the same purpose , so instead of defining the method externally we can define inline methods with the help of lambda expression and pass it to the Where() extension method as parameter.

Example :Return all Female Employees from List of Employee.

Method 1. Using external method.


    public class Program
    {
        public static void Main()
        {

            List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="UnMarried",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = employees.Where(Condition1);
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);

            }

            Console.ReadLine();

        }
        public static bool Condition1(Employee emp)
        {
            if (emp.Gender == "Female")
            {
                return true;
            }
            return false;
        }     

Output:

Output
Output

Method 2. Using Lambda expression.


      public static void Main()
        {
         List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = employees.Where(e=>e.Gender=="Female");
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);

            }

            Console.ReadLine();
        }

Output:

Output
Output

Example 2. Find all unmarried male employees whose salary is less than 40000.

Method 1. With External method.


   public class Program
    {
        public static void Main()
        {
            List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = employees.Where(Condition);
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);
            }

            Console.ReadLine();

        }
        public static bool Condition(Employee emp)
        {
            if (emp.Gender == "Male" && emp.Salary<40000 && emp.MaritalStatus=="UnMarried")
            {
                return true;
            }
            return false;
        }
   }

Output:

Output
Output

Method 2. With Lambda expression


  public class Program
    {
        public static void Main()
        {
            List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = employees.Where(e=>e.Gender=="Male" && e.Salary<40000 && e.MaritalStatus=="UnMarried");
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);
            }

            Console.ReadLine();

        }
        public static bool Condition(Employee emp)
        {
            if (emp.Gender == "Male" && emp.Salary<40000 && emp.MaritalStatus=="UnMarried")
            {
                return true;
            }
            return false;
        }      
   }

Output:

Output
Output

Where Operator with SQL-Like query syntax.

So far we have learnt to use Where operator using Extension methods , the same can be achieved with SQL like query syntax as shown in below examples.

Example 1: Return all Female Employees from List of Employee.


  public class Program
    {
     public static void Main()
        {
            List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = from e in employees
                           where e.Gender == "Female"
                           select e;
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);
            }
            Console.ReadLine();
        }

Output:

Output
Output

Example 2. Find all unmarried male employees whose salary is less than 40000.


   public class Program
    {
        public static void Main()
        {
            List<Employee> employees = new List<Employee>() 
            {
                new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                 new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000},
                 new Employee(){Id=3,Name="Vikash",Gender="Male",MaritalStatus="UnMarried",Phone=123458,Salary=40000},
                 new Employee(){Id=4,Name="Neha",Gender="Female",MaritalStatus="UnMarried",Phone=123459,Salary=50000},
                 new Employee(){Id=5,Name="Nivi",Gender="Female",MaritalStatus="UnMarried",Phone=123450,Salary=60000},
                 new Employee(){Id=6,Name="Abhijeet",Gender="Male",MaritalStatus="Married",Phone=123451,Salary=70000},
                 new Employee(){Id=7,Name="Ankit",Gender="Male",MaritalStatus="Married",Phone=123452,Salary=80000}
            };
            var filtered = from e in employees
                           where e.Gender == "Male" && e.Salary<40000 && e.MaritalStatus=="UnMarried"
                           select e;
            foreach (var emp in filtered)
            {
                Console.WriteLine("Name:{0}| Salary:{1} | MaritalStatus:{2}",emp.Name,emp.Salary,emp.MaritalStatus);
            }
            Console.ReadLine();
        }
  }

Output:

Output
Output

Note : The query written in SQL like syntaxes are translated into their Extension method syntaxes, internally , before they execute.

OfType

As the name suggests , OfType Operator simply returns all the elements of a given type from the collection . In other words ,The OfType operator filters the collection based on the ability to cast an element in a collection to a specified type. , means , if it can cast the element to the given type it returns them otherwise simply skips them.

OfType in Method Syntax

You can use OfType<TResult>() extension method in linq method syntax as shown below.


  IList mixedList = new ArrayList();
  mixedList.Add(100);
  mixedList.Add("sharpencode");
  mixedList.Add("tutorial");
  mixedList.Add(300);
  mixedList.Add(new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                         new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000});

  var stringResult = mixedList.OfType<String>();
  var intResult = mixedList.OfType<int>();
  var empList = mixedList.OfType<Employee>();

OfType in Query Syntax

Example :Filter the collection based on each element type.


 IList mixedList = new ArrayList();
 mixedList.Add(100);
 mixedList.Add("sharpencode");
 mixedList.Add("tutorial");
 mixedList.Add(300);
 mixedList.Add(new Employee(){Id=1,Name="Sachin",Gender="Male",MaritalStatus="UnMarried",Phone=123456,Salary=20000},
                         new Employee(){Id=2,Name="Arjun",Gender="Male",MaritalStatus="Married",Phone=123457,Salary=30000});
 var result = from s in mixedList.OfType<string>()
                select s;
var intResult = from s in mixedList.OfType<int>()
                select s;
var empList = from s in mixedList.OfType<Employee>()
                select s;