Before moving to this InClause concept let's create a model and add the dummy values to it,
- public class Employee {
- public int ID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Location {
- get;
- set;
- }
- public decimal Income {
- get;
- set;
- }
- }
- List < Employee > employees = new List < Employee > {
- new Employee {
- ID = 1, Name = "Gnanavel Sekar", Location = "India", Income = 1500000
- },
- new Employee {
- ID = 2, Name = "Robert A", Location = "India", Income = 14000000
- },
- new Employee {
- ID = 3, Name = "Gokul", Location = "UK", Income = 18000000
- },
- new Employee {
- ID = 4, Name = "Karthik", Location = "USA", Income = 1250000
- },
- new Employee {
- ID = 5, Name = "Subash S", Location = "India", Income = 1280000
- },
- };
- foreach(var employee in employees) {
- Console.WriteLine("ID : " + employee.ID + " Name : " + employee.Name + " Income : " + employee.Income);
- }
Run your application,
Okay! Let's come to the concept. If we want to apply more than one condition we can do so with where condition, but if want to determine whether the specified value matches any value in a list for a particular column it means we have to use the InClause.
The above image represents the collection of the employee. Now we're going to filter for locations India and UK using InClause. We will see this in both the LINQ and lambda query.
Linq query
Let's take an example, I wanted to search the employees whose location are India and UK. For that, I have created one array in the name of myInClause which holds the locations to filter.
- var myInClause = new string[] { "India", "UK"};
- var LinqResult = from emp in employees
- where myInClause.Contains(emp.Location)
- select emp;
- foreach (var employee in LinqResult)
- {
- Console.WriteLine("ID : " + employee.ID + " Name : " + employee.Name + " Income : " + employee.Income);
- }
Result,
Lambda Query
- Console.WriteLine("Lamda");
- Console.WriteLine("***************");
- var results = employees.Where(x => myInClause.Contains(x.Location));
- foreach (var employee in LinqResult)
- {
- Console.WriteLine("ID : " + employee.ID + " Name : " + employee.Name + " Location :" + employee.Location + " Income : " + employee.Income);
- }
Result
We have specified locations as India and UK in both LINQ and lambda queries. We can see there are just three employees from India and UK. So we should be getting the above output from both queries.
Try your own for the below list,
- var myInClauseInt = new int[] { 4, 5 };
I hope it's helpful.