-2

I want In operator in mvc Linq.

like this sql (stud_ID is int, primary key and auto increment):

select * from student where stud_ID in (1,4,6,10,5);

how can I adapt for linq this sql?

like

List<int> nl = new List<int>();
nl.add(1);
nl.add(4);
nl.add(6);
nl.add(10);
nl.add(5);
List<student> students = db.student.where(a => a.stud_ID.In(nl)).toList();
//this code is fitting from my mind :D

or the other scenario

List<student> st = db.studentOrderBy(x => Guid.NewGuid()).Take(5); //only for create auto list student type
List<student> students = db.student.where(
    a => a.stud_ID.In(st.Select(b => b.stud_ID).toList())
).toList(); //again fitting

I can this

List<student> students = new List<student>();
foreach(var item in nl)
{
    students.add(db.student.where(a => a.stud_ID == item).First());
}

but I dont want to use for or foreach or do-while or while :D

tereško
  • 58,060
  • 25
  • 98
  • 150
  • possible duplicate of [Linq to Entities - Sql "IN" clause](http://stackoverflow.com/questions/857973/linq-to-entities-sql-in-clause) –  Mar 24 '14 at 08:23
  • thanks for your answer. did I find but cant find. This answer work. thanks. – user1811872 Mar 24 '14 at 08:42

2 Answers2

0

try this:

List<student> students = db.student.where(a => nl.Contains(a.Stud_ID)).toList();

This checks, if the student ID is present in the List nl. If so, the student gets returned in the result.

Your second requirement is different, if I understand it correctly. You have two collections of studentes, and want to know which students are also in st.

var intersectedList = students.Intersect(st);
Marco
  • 22,856
  • 9
  • 75
  • 124
-1

Try this

List<student> students = db.student.Where<student>(a =>  nl.Contains(a.stud_ID)).ToList<student>();
Johann Blais
  • 9,389
  • 6
  • 45
  • 65