根据正在解析的id列表查询出数据库
本文关键字:列表 id 查询 数据库 | 更新日期: 2023-09-27 18:24:26
所以我得到了一个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键入强制转换,并将强制转换键入给student。有没有其他方法可以在不需要foreach()的情况下使用linq来实现这一点?
您将得到一个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();