无法在C#中隐式转换类型'System.Collections.Generic.List <AnonymousType#1>

gar*_*ing 2 c# linq

嗨,我是编程新手,请您帮助我:

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

我的代码是:

List<IncByYrMonthModel> 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;
Run Code Online (Sandbox Code Playgroud)

我的模特是:

public class IncByYrMonthModel
{
    public string Year { get; set; }
    public string Month { get; set; }
    public string Total { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

更新的代码

public List<IncByYrMonthModel> GetYrMonth2(HttpSessionStateBase session, int id, int _StrYear)
{
    List<IncidentsModel> incidentsViewModel = ViewModelService.Fetch<List<IncidentsModel>>(session, id);

    List<IncByYrMonthModel> 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;
    }
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 5

你应该改变这个

select new { d.Key.month, d.Key.year, count = d.Count() }
Run Code Online (Sandbox Code Playgroud)

对此

select new IncByYrMonthModel { Month = d.Key.month, Year = d.Key.year, Total = d.Count() }
Run Code Online (Sandbox Code Playgroud)

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