所以我得到了一个正在解析我的构造函数的ID列表。工作是获取与列表中的ID匹配的记录。到目前为止,我已经尝试过:
void displayChosenIDs(List<int> ids)
{
bool flag = false;
List<Student> student_record = new List<Student>();
//Display the interests IDs on grid
using(StudentEntities context = new StudentEntities())
{
//get students correspond to ones in the list
foreach(int value in ids)
{
Student rec = (Student)(from o in context.Students
where o.ID.CompareTo(value) == 0
select o);
student_record.Add(rec);
}
}
我收到错误消息,指出无法使用我的linq键入强制转换并输入强制转换为学生。有没有其他方法可以使用linq而不需要foreach()?
答案 0 :(得分:1)
您收到InvalidCastException
因为select会返回IQueryable<Student>
,而不是Student
。您可以使用Where
和Contains
:
student_record.AddRange(context.Students.Where(x => ids.Contains(x.ID)));
// Or:
var student_record = context.Students.Where(x => ids.Contains(x.ID)).ToList();