LINQ Equivalent of SQL’s “IN” keyword

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 .

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

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

2 Comments

  1. Giedrius August 22, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
Column Alias and Square brackets in SQL Query.
When we want to specify a alias for a column in SQL Query , we tend to use the double quotes or sing...