Pass an int array in the where section of the LINQ query

There is a class

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

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 writing a request. Thanks everyone for the answers, am I also looking for support for speeches with a large list of recordings? It will be great if you can add me, a simple explanation of the request will work inside?

+6
source share
3 answers

If you want to find these students from a list whose identifier is in the ids array, then:

 var list = from s in stundentList where ids.Contains(s.ID) select s; 
+10
source

to try

 Var list = studentList.Where(s=>ids.Contains(s.id)).ToList(); 
+4
source

I think that the answers already provided will be fast enough, but just in case after testing, you will find that it is too slow: you can try to convert the list of students to a dictionary before doing a search.

You should only use this after careful time checks, as in most cases it will be much slower!

 public static List<Student> FilteredStudents(int[] targetIds) { var allStudents = GetAllStudents().ToDictionary(student => student.id); var result = new List<Student>(); foreach (int id in targetIds) { Student student; if (allStudents.TryGetValue(id, out student)) { result.Add(student); } } return result; } 
+1
source

All Articles