Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple select query in linq

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?

like image 473
Cute Bear Avatar asked Oct 12 '12 12:10

Cute Bear


People also ask

How do I select a query 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.

What is select in LINQ C#?

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.

How do I run a SQL query in LINQ?

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.

How do I select a query in C#?

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.


1 Answers

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();
like image 99
Darren Avatar answered Oct 11 '22 10:10

Darren