在LINQ Query的where子句中传递int数组
有一节课
Public class Student { int id; int rollNum; String Name; }
一个方法
Public List 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); }
我想编写一个方法,将一个int数组作为输入并返回一个List
Public List FilterStudentsByID(int[] ids,List 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; }
编写查询的任何帮助。 谢谢大家的答案,我也在寻找保持大型记录列表的表现? 如果你能加我简单的查询解释将在内部工作将是伟大的??
如果您希望从列表中找到ID为ids
数组的学生,那么:
var list = from s in stundentList where ids.Contains(s.ID) select s;
尝试
Var list = studentList.Where(s=>ids.Contains(s.id)).ToList();
我认为已经给出的答案足够快,但是在测试后你发现它太慢了:你可以尝试在进行搜索之前将学生列表转换成字典。
你应该只在经过仔细的计时测试后使用它,因为对于大多数情况来说它可能会慢得多!
public static List FilteredStudents(int[] targetIds) { var allStudents = GetAllStudents().ToDictionary(student => student.id); var result = new List (); foreach (int id in targetIds) { Student student; if (allStudents.TryGetValue(id, out student)) { result.Add(student); } } return result; }