0

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

我在这里错过了什么吗?

4

2 回答 2

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)
                                        });
于 2013-08-02T01:53:15.587 回答
1

您正在尝试将匿名类型的列表放入vwHour.

如果要返回匿名类型的列表,只需将变量类型更改为var

var Total = (  ...

如果您确实希望此查询返回 列表vwHour,则需要修改select

select new vwHour {  ...

但这要求 vwHour 有一个Total属性和一个string Date属性。但是我们可以从group byandselect子句中看到,您的vwHour类型已经有一个Date似乎是 a 的属性Nullable<DateTime>。因此,select如果您将其更改为 create vwHours,它将无法正常工作。

如果您的 vwHour 课程是这样的:

class vwHour
{
    public object UserName { get; set; }
    public DateTime? Date { get; set; }
    public int Hours { get; set; }
}

那么这将起作用:

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), });
于 2013-08-02T02:06:58.173 回答