Linq 如何从查询中获取前1条记录
假设查询中有5条记录,如何获取前1条记录?这是我当前的代码Linq 如何从查询中获取前1条记录,linq,Linq,假设查询中有5条记录,如何获取前1条记录?这是我当前的代码 public Application GetByUserIdAndVersion(int userId, string version) { VettingDataContext dc = new VettingDataContext(_connString); return (from a in dc.Applications where a.UserId == userId &&
public Application GetByUserIdAndVersion(int userId, string version)
{
VettingDataContext dc = new VettingDataContext(_connString);
return (from a in dc.Applications
where a.UserId == userId && a.chr_Version == version
select a).SingleOrDefault<Application>();
}
公共应用程序GetByUserId和version(int-userId,字符串版本)
{
VettingDataContext dc=新的VettingDataContext(_connString);
返回(从dc.Applications中的
其中a.UserId==UserId&&a.chr\u Version==Version
选择一个.SingleOrDefault();
}
只需使用FirstOrDefault()
即可:
return (from a in dc.Applications
where a.UserId == userId && a.chr_Version == version
select a).FirstOrDefault<Application>();
返回(从dc.应用程序中的
其中a.UserId==UserId&&a.chr\u Version==Version
选择一个.FirstOrDefault();
SingleOrDefault()
将引发异常,如果有多条记录,FirstOrDefault()
将只接受第一条记录
此外,您不必强制转换到
应用程序
-您的记录已经是应用程序
类型。对于第一条记录,您可以尝试:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault();
第一次使用时:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N);