【发布时间】:2023-04-09 04:45:01
【问题描述】:
我需要使用 Select 运算符以 linq 方法语法对数据进行整形,以返回具有 Name 和 Age 属性的匿名对象集合。我知道如何编写查询语法来实现这一点,但无法做到这一点方法语法
查看 2 段代码,第 1 段运行正常,第 2 段出现错误指示 严重性代码 描述 项目文件行抑制状态 “错误 CS1061 'IGrouping' 不包含 'StudentName' 的定义,并且找不到可访问的扩展方法 'StudentName' 接受类型为 'IGrouping' 的第一个参数(您是否缺少 using 指令或程序集引用?)”
var studentsGroupByStandard = from s in ObjectsMisc.studentList
group s by s.StandardID into sg
orderby sg.Key
select new { sg.Key, sg };
var testS = ObjectsMisc
.studentList
.GroupBy(sg => sg.StandardID)
.OrderBy(sg => sg.Key).Select(sg => new {
Name = sg.StudentName,
Age = s.Age
});
所以第二件产生了设计错误
【问题讨论】:
-
那么问题是什么?在
GroupBy中,您会得到组,它们包含一个密钥,然后是一组学生(在本例中)。你说var testS =,但是你有没有想过你想从这个查询中得到什么?你想要什么结果? -
不应该只是
Select(sg => new { sg.Key, sg })吗? -
第二个查询甚至与第一个查询不相似。看看select语句中的极端差异
-
错误告诉你,一组学生没有
StudentName。我觉得 Sweeper 的修正是对的。 -
没有人读过异常信息 :(