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

标签 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;

我的模型是:

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

更新了代码

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;
    }

最佳答案

你应该改变这个

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 列表,这是不可能的。

关于c# - 无法在 C# 中隐式转换类型 'System.Collections.Generic.List<AnonymousType#1>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33025951/

相关文章:

c# - 如何使用C#读取DEM文件?

c# - 使用 mimekit/mailkit 过滤带附件的电子邮件

c# - SQLite LINQ 提供程序数据上下文

c# - 在 linq 查询中切换大小写

c# - 生成 List<string> 和 List<int> 之间的列表保存/创建映射

c# - const/readonly 与 Cheat Engine 等程序

C# - 从项目的发布版本中排除单元测试

c# - 如何检查两个列表是否具有相同的值并从其中一个列表中删除值

c# - LINQ 搜索相似字符串(名称)

c# - 返回一个 IQueryable<dynamic> 以在父方法中进行过滤