Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass int array in where clause of LINQ Query

Tags:

c#

linq

generics

There is a class

Public class Student
{
  int id;
  int rollNum;
  String Name;
}

a method

Public List<Student> GetAllStudents()
{
  var studentList = GetMeAll(); // Simple select * query to get all students
  //unfortunately i can't make changes in this method so have to write a linq query to       //filter data.
  //getting int array ids correctly from some method
   var filterList = FilterStudentsByID(ids,StudentList);
}

I want to write a method that takes an int array as input and returns a List

Public List<Student> FilterStudentsByID(int[] ids,List<student> studentList)
{
  //There should be a linq query , but I am new to linq so don't know how to write this.
  Var list = from  studentList in ..... don't know much;
}

Any help in writing the query. Thank you all for Answers, I am also looking for maintain the performances with large list of records ?? It will be great if you can add me simple explanation of the query will work internally ??

like image 793
ankur Avatar asked Mar 13 '13 08:03

ankur


2 Answers

If you are looking to find those students from the list whose id's are present in the ids array then:

var list = from s in stundentList
           where ids.Contains(s.ID)
           select s;
like image 199
Habib Avatar answered Oct 16 '22 23:10

Habib


try

Var list = studentList.Where(s=>ids.Contains(s.id)).ToList();
like image 39
Damith Avatar answered Oct 16 '22 23:10

Damith