【问题标题】:Select in Method Syntax C# - returns a collection of anonymous object在方法语法 C# 中选择 - 返回匿名对象的集合
【发布时间】: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 的修正是对的。
  • 没有人读过异常信息 :(

标签: c# linq methods group-by


【解决方案1】:

第一个查询的等效方法语法是

var testS = ObjectsMisc.studentList
    .GroupBy(s => s.StandardID)
    .OrderBy(sg => sg.Key)
    .Select(sg => new { sg.Key, sg})

但是,这不会选择 StudentNameAge 属性,而是选择整个学生对象。

如果您的学生有一个StudentName 和一个Age 属性,并且您想选择按StandardId 分组的这些属性,则将是以下方法语法

var testS = ObjectsMisc.studentList
    .GroupBy(s => s.StandardID)
    .OrderBy(sg => sg.Key)
    .Select(sg => new { sg.Key, Students = sg.Select(s => new { s.StudentName, s.Age }) })

【讨论】:

  • 谢谢 wertzui,第一段代码很好,但不是第二段,我在“sg.Select(s => new { s.StudentName, s.Age”下得到一条红色的波浪线以下 2 个错误:错误 CS1026 ) 预期和 ************ 错误 CS0746 无效的匿名类型成员声明符。必须使用成员分配、简单名称或成员访问来声明匿名类型成员。
  • 如错误所示,缺少) 并且未声明成员名称。我更正了代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多