Linq 结果到 IEnumerable 无效转换
Linq 用户的问题:每当我尝试从 revs
获取 IEnumerable
时,都会收到 InvalidCastexception: Specifiedcast is not valid
进行 Linq 查询。数据库已填充,它应该返回值。
具体来说,错误发生在 List
有什么想法吗?
short ret;
using (DataContext db = new DataContext())
{
var play = from p in db.PDP
where p.ID == id
select p;
var revs = play.OrderByDescending(p => p.revision);
List<PDP> rev = revs.ToList();
var revNum = revs.ToList().Count() > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
编辑
我已经澄清了代码的某些部分。
编辑2rev
作为调试变量存在,以缩小错误的范围。
原来的代码是:
short ret;
using (GasForecastDataContext db = new GasForecastDataContext())
{
var play = from p in db.PDP
where p.Play_ID == play_id
select p;
var revs = play.OrderByDescending(p => p.revision);
var revNum = revs.Count > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
Question for Linq users out there: I'm getting an InvalidCastexception: Specified cast is not valid
whenever I try to obtain an IEnumerable
from revs
after making the Linq query. There database is populated and it should be returning values.
Specifically, the error is occurring on the line List<PDP> rev = revs.ToList<PDP>();
Any ideas what's going on?
short ret;
using (DataContext db = new DataContext())
{
var play = from p in db.PDP
where p.ID == id
select p;
var revs = play.OrderByDescending(p => p.revision);
List<PDP> rev = revs.ToList();
var revNum = revs.ToList().Count() > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
EDIT
I've clarified some parts of the code.
EDIT 2rev
exists as a debugging variable to narrow down where the error was.
The original code was:
short ret;
using (GasForecastDataContext db = new GasForecastDataContext())
{
var play = from p in db.PDP
where p.Play_ID == play_id
select p;
var revs = play.OrderByDescending(p => p.revision);
var revNum = revs.Count > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您声明“rev”列表变量是否有具体原因? “Count()”和“First()”可在 IEnumerable 接口 (“revs”) 上使用。
Is there a specific reason you're declaring the "rev" list variable at all? "Count()" and "First()" are available on IEnumerable interface ( "revs" ).
db.PDP 中的元素似乎是 PDP 之外的某种类型,或者如果是 PDP,则可能位于另一个命名空间中。
It seems like the elements in
db.PDP
are some type other thanPDP
, or if it isPDP
, it may be in another namespace.它不仍然是一个 IQueryable 吗?
rev 可能会被转换为 IEnumberable,但 revs 可能仍然是 IQueryable。
您也许可以在转速上调用 ToList()。
Wouldn't it still be an IQueryable?
rev could probably be cast as an IEnumberable, but revs is probably still IQueryable.
You might be able to call ToList() on revs.
试试这个:
我刚刚添加了泛型的类型。
Try this:
I just added the type for the generic.