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.

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

  1. Giedrius
    August 22, 2011
    Reply

    well, you should be aware, that there’s limited count of items, that are looked in, if I recall it correctly it’s 2100.

  2. August 22, 2011
    Reply

    Thanks for the info

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...