I came across the requirement to use the “IN” equivalent of LINQ when using Entity Framework . I am sure most of the .NET Developers would also have come across a situation to use “IN” in LINQ.
LINQ Equivalent of SQL’s “IN” keyword
Here’s an example .
The SQL Query looks like this
SELECT * FROM MOVIES WHERE MOVIENAME IN ('Velayutham','Nanban(3 idiots)','Pagalvan','Yohan Adhyayam Ondru','Maalai Neram Mazhaithuli')
When using LINQ , We can use the Contains Keyword which is the equivalent of “IN” keyword in SQL .
Below is the sample using LINQ Query
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] upcoming = new string[] { "Velayutham", "Nanban", "Pagalvan","Yohan Adhyayam Ondru","Maalai Neram Mazhaithuli" }; List<Movie> Movies = new List<Movie>(); Movies.Add(new Movie { Name = "Ghilli", Director = "Dharani" }); Movies.Add(new Movie { Name = "Kaavalan", Director = "Siddique" }); Movies.Add(new Movie{ Name ="Velayutham" , Director ="Jayam Raja" }); Movies.Add(new Movie{ Name ="Pagalvan" , Director = "Seeman" }); Movies.Add(new Movie{ Name ="Yohan" , Director = "Gautham Menon" }); var UpcomingMovies = (from m in Movies where upcoming.Contains(m.Name) select m ).ToList(); } } public class Movie { public string Name { get; set; } public string Director { get; set; } }
Using Lambda Expressions
var UpcomingMoviesByLambda = Movies.Where(c => upcoming.Contains(c.Name));
What is Entity Framework ?
Know more about Entity Framework from MSDN
2 Comments
well, you should be aware, that there’s limited count of items, that are looked in, if I recall it correctly it’s 2100.
Thanks for the info