无法在C#中隐式转换类型’System.Collections.Generic.List

嗨,我是编程的新手,请你帮我解决这个问题:

我在“To.List()”中收到错误错误1无法将类型’System.Collections.Generic.List’隐式转换为’System.Collections.Generic.List

我的代码是:

List GroupedList = (from p in incidentsViewModel group p by new { month = p.DateClosed.Value.Month, year = p.DateClosed.Value.Year } into d select new { d.Key.month, d.Key.year, count = d.Count() }).ToList(); return GroupedList; 

我的模型是:

 public class IncByYrMonthModel { public string Year { get; set; } public string Month { get; set; } public string Total { get; set; } } 

更新的代码

 public List GetYrMonth2(HttpSessionStateBase session, int id, int _StrYear) { List incidentsViewModel = ViewModelService.Fetch<List>(session, id); List GroupedList = (from p in incidentsViewModel group p by new { month = p.DateClosed.Value.Month, year = p.DateClosed.Value.Year } into d select new IncByYrMonthModel { Month = d.Key.month, Year = d.Key.year, Total = d.Count() }); return GroupedList; } 

你应该改变它

 select new { d.Key.month, d.Key.year, count = d.Count() } 

对此

 select new IncByYrMonthModel { Month = d.Key.month, Year = d.Key.year, Total = d.Count() } 

第一种情况的问题是你有一个匿名类型的对象序列,你试图将它们转换为IncByYrMonthModel列表,这是不可能的。

您基本上是在尝试分配匿名类型

new {d.Key.month,d.Key.year,count = d.Count()}

对你的对象。 而不是选择新的{…},只需选择新的IncByYrMonthModel(){…}来填充您的对象。