我想将linq结果输出到IEnumerable列表但是我得到了一个强制转换错误:
IEnumerable<vwHour> Total = (from p in vwHours.Where(ph => ph.UserName == UserName())
group p by p.Date into g
select new {Date = g.Key.Value.ToString("mm/dd/yy"), Total = g.Sum(p => p.Hours),});
错误讯息:
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<UI.Models.vwHour>'. An explicit conversion exists (are you missing a cast?)
我在这里遗漏了什么吗?
答案 0 :(得分:2)
IEnumerable<vwHour> Total = (from p in vwHours.Where(ph => ph.UserName == UserName())
group p by p.Date into g
select new vwHour(){ //<----
Date = g.Key.Value.ToString("mm/dd/yy"),
Total = g.Sum(p => p.Hours)
});
答案 1 :(得分:1)
您正尝试将匿名类型列表放入变量中,以获得vwHour
列表。
如果要返回匿名类型列表,只需将变量类型更改为var
:
var Total = ( ...
如果您确实希望此查询返回vwHour
列表,则需要修改select
:
select new vwHour { ...
但这要求vwHour具有Total
属性和string Date
属性。但我们可以从group by
和select
条款中看到,您的vwHour
类型已经有Date
属性,似乎是Nullable<DateTime>
。因此,如果您将select
更改为创建vwHour
,则class vwHour
{
public object UserName { get; set; }
public DateTime? Date { get; set; }
public int Hours { get; set; }
}
无法正常工作。
如果您的vwHour类是这样的:
IEnumerable<vwHour> Total =
(from p in vwHours.Where(ph => ph.UserName == UserName())
group p by p.Date into g
select new vwHour { Date = g.Key, Hours = g.Sum(p => p.Hours), });
然后这会起作用:
{{1}}