c# - Linq GroupBy 表达式引发 AnonymousType 异常
问题描述
我有一个查询,它返回一个IEnumerable
用于显示值表的查询。
我想按模型的字段( )对表格(使用<H3/>
元素)进行分组。DateTime
StartTime
我更改了模型以使用适当的泛型:
IEnumerable<IGrouping<DateTime, FooViewModel>> routes;
我通过FromSQL
查询填充模型:
routes = (IEnumerable<IGrouping<DateTime, FooViewModel>>)await _context.FooViewModels
.FromSql(@"SELECT ..."
)
.GroupBy(r => new { r.StartTime.Date })
.ToListAsync();
虽然代码通过了设计时要求,但在运行时出现错误:
Unable to cast object of type 'System.Collections.Generic.List`1[System.Linq.IGrouping`2[<>f__AnonymousType5`1[System.DateTime],FooViewModel]]' to type 'System.Collections.Generic.IEnumerable`1[System.Linq.IGrouping`2[System.DateTime,FooViewModel]]'.
我做错了什么?
解决方案
正如错误试图告诉您的那样,您不能将匿名类型作为DateTime
.
由于您的视图接受一组DateTime
s,因此您需要传递一个DateTime
lambda 以GroupBy()
使其具有相同的类型。
推荐阅读
- log4j - 如何从日志消息 log4j 中删除或替换换行符
- python - python groupby聚合函数错误
- c++ - 数组比较模板 operator== 不适用
- python - 无法理解特定的 Python 3 代码
- audio - 适用于 Android 设备的 Superpowered Player 大多数时间会在 2 到 3 秒后停止
- angular - 角度编译器似乎不适用于 tsconfig 中的“路径”
- python - Python:如果两列没有出现在另一个熊猫列中,如何在熊猫中删除行?
- java - RandomAccessFile 读取错误的整数
- excel - 将 D 列中的所有值从具有未知行数的未知工作表复制到主工作表中的单个 A 列值
- arrays - 保存阵列猫鼬