在linq查询中聚合时出错

时间:2013-08-02 01:14:48

标签: c# asp.net-mvc linq

我想将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?)

我在这里遗漏了什么吗?

2 个答案:

答案 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 byselect条款中看到,您的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}}