How to implement WHERE IN clause in Linq or Entity Framework query

WHERE IN clause is most important for filter more then options in single line argument. We can easily implement Where in clause in SQL Server or My SQL because it's inbuilt operator of it. In this article i will show you how to use Where In clause in Linq or entity framework query.
Where In syntax in SQL SERVER
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
First we make one class Employee having fields Id, Name and salary. Using GetEmployees() method we will get list of Employees.
public class Employee
        public int Id { get; set; }
        public string Name { get; set; }
        public double Salary { get; set; }

        public List GetEmployees()
            List employees = new List()
                new Employee { Id = 1, Name = "Bhavik", Salary = 10000 },
                new Employee { Id = 2, Name = "Sohil", Salary = 12000 },
                new Employee { Id = 3, Name = "Mitul", Salary = 14000 },
                new Employee { Id = 4, Name = "Vikram", Salary = 11000 },
                new Employee { Id = 5, Name = "Pradip", Salary = 13000 }
Now take gridview to display list of employees. and use GetEmployees() method to bind it. We will get five employees in list.

How to use Where in clause in Linq

To use where in clause we will take one Int array to filter our employee list
int[] ids = new[] { 1, 3, 5 };
Now We will Apply filter to existing list
// create Employee class instance
Employee employee = new Employee();

// Get all employees
var employees = employee.GetEmployees();

// Id list for filter
int[] ids = new[] { 1, 3, 5 };

//apply filter
var filterList = (from e in employees
                  where ids.Contains(e.Id)
                  select e);

// bind gridview
gvList.DataSource = employees;
How to use Where in clause in Linq
Download Sample Code


Popular posts from this blog

12 opensource and free MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in