有一个班级
Public class Student
{
int id;
int rollNum;
String Name;
}
方法
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);
}
我想编写一个方法,将int数组作为输入并返回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;
}
编写查询时的任何帮助。谢谢大家的答案,我也在寻找保持大型记录列表的表现?如果你可以添加我简单的查询解释将在内部工作会很棒吗?
答案 0 :(得分:10)
如果您希望从ids
数组中出现id的列表中找到那些学生,那么:
var list = from s in stundentList
where ids.Contains(s.ID)
select s;
答案 1 :(得分:5)
试
Var list = studentList.Where(s=>ids.Contains(s.id)).ToList();
答案 2 :(得分:1)
我认为已经给出的答案足够快,但以防万一在测试后你发现它太慢了:你可以尝试在进行搜索之前将学生列表转换为字典。< / p>
你应该只在经过仔细的时间测试之后使用它,因为对于大多数情况来说它可能会慢得多!
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;
}