How to simulate IN Clause in LINQ queries
Hi,
When working with the LINQ queries for SQL one of the common queries that we need to run is the select query with IN clause. In SQL IN clause is used to provide more than one value to match in the where clause.
Something like the query below
Select * from Table
where column1 in (‘Value1’,
‘Value2’, ‘Value3’)
To do a similar query in LINQ we can use
var
list = from t in table
where
t.column1 = Value1’
And t.column1 =
Value2’
t.column1 = Value3’
Select t
But what if the number of values are not known is design time, coming from another list etc?
In that case you need to write the LINQ query like this.
List<string> names = new List<string>();
names.Add("Value1");
names.Add("Value2");
names.Add("Value3");
names.Add("Value4");
var list = from t in table
where
names.contains(t.column1)
select t
You can pass the value of a full table also by querying
the table first and then fetching all the values of the
table in the list.
Vikram