Lets say I have a student table and I want to display the student with ID 1.
SELECT *
FROM STUDENT ST
WHERE ST.ID = 1
This is how I achive this in Linq.
StudentQuery = from r in oStudentDataTable.AsEnumerable()
where (r.Field<int>("ID") == 1)
select r;
oStudentDataTable = StudentQuery.CopyToDataTable();
but what if I want to display the students with these ids 1,2,3,4,5..
SELECT *
FROM STUDENT ST
WHERE ST.ID IN (1,2,3,4,5)
How can I achieve this in Linq?
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
Add a LINQ to SQL class file. Drag and drop the respective table. Now, copy this code in the main method. We are creating an instance of sample datacontext class and then we are using this ExecuteQuery method to execute the SQL query.
Open(); SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn); //command. Parameters. AddWithValue("@zip","india"); int result = command. ExecuteNonQuery(); // result gives the -1 output.. but on insert its 1 using (SqlDataReader reader = command.
Use .Contains
var list = new List<int> { 1, 2, 3, 4, 5 };
var result = (from r in oStudentDataTable.AsEnumerable()
where (list.Contains(r.Field<int>("ID"))
select r).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With