If you have been worked with T-SQL, You know that we have an IN keyword in our WHERE clause like the following instance:
SELECT * FROM MyTable WHERE ID IN (1, 2, 3)
In the example above, I selected a table from my database named "MyTable" and then select rows that the ID column of each row is equal to 1, 2 and 3. If rows are exists so the select statement should return 3 results.
When you're working with .NET framework 3.5, You may need to do such a thing using LINQ to SQL. In this post I'll show you how to do that.
Before we get started, lets review some simple LINQ commands and basics:
- In order to start using LINQ to SQL, You have to create a new item named LINQ to SQL Class by right click on your project in solution explorer, point to add menu and select new item as shown below:
- In the new item windows select LINQ to SQL class and name it SampleDb:
- Now it's time to add some SQL tables from our SQL Server Database by drag them from Server Explorer (Available in View menu) and drop them to our LINQ to SQL Class designer. When you do such a thing, Visual Studio adds some classes with properties and methods to your project automatically.
- We can add some code in order to access our data. First you have to declare a new variable from our LINQ to SQL class. By default, the name of our LINQ to SQL class is YouClassName + DataContext. So here it is:
private SampleDbDataContext db = new SampleDbDataContext();
You can select, insert, update and delete rows from your selected table(s). What we're looking for right now is to select 4 specific rows from our table to simulate SQL "IN" keyword. In order to do this, have to create an array of your selected IDs. In this case I want to select rows with IDs (1, 2, 3); So just create an integer array as following:
int[] MySelectedRows = {1, 2, 3} ;
Now lets write some codes in order to select some columns from our table:
var MyData = (from data in db.Mails
select data);
With the code above, you can select all rows in Mails table. Now we have to specify to select only rows with IDs 1, 2 and 3 so we must add a where clause to our select statement:
var MyData = (from data in db.Mails
where data.MailID == Convert.ToInt32(MySelectedRow)
select data);