[英]Select in Method Syntax C# - returns a collection of anonymous object
我需要使用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
});
所以第二件产生设计错误
第一个查询的等效方法语法是
var testS = ObjectsMisc.studentList
.GroupBy(s => s.StandardID)
.OrderBy(sg => sg.Key)
.Select(sg => new { sg.Key, sg})
但是,这不会选择StudentName
和Age
属性,而是选择整个学生对象。
如果您的学生具有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 }) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.