我如何转换[AnonymousType#1]或预定义它
本文关键字:AnonymousType#1 预定义 何转换 转换 | 更新日期: 2023-09-27 18:08:25
我得到这个错误
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<object>'
运行3.5 .net以前从未有过此问题。不确定修改了什么
错误发生在select new {ITEMID = p. pressreleaseid};
我已经试过了,但是一直得到不同的转换错误。
StringBuilder textStr = new StringBuilder();
var years = (from ys in db.tblPressReleases orderby ys.prdate descending select ys.prdate.Year).Distinct();
ddlYear.DataSource = years;
ddlYear.DataBind();
ddlYear.Items.Insert(0, new ListItem("Year", ""));
IQueryable<object> pressreleases ;
DateTime startdate, enddate;
if (this.iFilterMonth != null && this.iFilterMonth > 0 && this.iFilterYear != null)
{
startdate = new DateTime((int)this.iFilterYear, (int)this.iFilterMonth, 1);
enddate = startdate.AddMonths(1);
pressreleases = from p in db.tblPressReleases
where p.prdate.Date >= startdate.Date && p.prdate.Date < enddate.Date
orderby p.prdate descending
select new { ITEMID = p.PRESSRELEASEID };
}
else if (this.iFilterYear != null)
{
startdate = new DateTime((int)this.iFilterYear, 1, 1);
enddate = new DateTime((int)this.iFilterYear + 1, 1, 1);
pressreleases = from p in db.tblPressReleases
where p.prdate.Date >= startdate.Date && p.prdate.Date < enddate.Date
orderby p.prdate descending
select new { ITEMID = p.PRESSRELEASEID };
}
else
{
pressreleases = (from p in db.tblPressReleases
orderby p.prdate descending
select new { ITEMID = p.PRESSRELEASEID }).Take(15);
}
dlDisplay.DataSourceID = "";
dlDisplay.DataSource = pressreleases;
dlDisplay.Visible = true;
dlDisplay.DataBind();
三个独立选项:
- 完全放弃匿名类型。你只有一个值,所以为什么不使用
select p.PRESSRELEASEID
? -
在
select
子句中强制转换:select (object) new { ITEMID = p.PRESSRELEASEID }
-
使用
var
声明变量,提供一个虚拟示例:var pressreleases = new[] { new { ITEMID = "" } }.ToQueryable();
作为题外话,我强烈建议重新考虑你的命名——无论是非常响亮的名字还是非常安静的名字;更常规的名称是pressReleases
(用于局部变量)和PressReleaseID
(用于属性)。