[英]Select in Method Syntax C# - returns a collection of anonymous object
I need to use Select operator to shape the data in a linq method syntax to return a collection of anonymous object with the Name and Age property.I know how to write a query syntax for achieving this but not able to do it with a method syntax 我需要使用Select运算符来形成linq方法语法中的数据,以返回具有Name和Age属性的匿名对象的集合。我知道如何编写查询语法来实现此目的但不能使用方法语法来执行此操作
See the 2 pieces of code, 1st one works fine, 2nd getting error indicating Severity Code Description Project File Line Suppression State "Error CS1061 'IGrouping' does not contain a definition for 'StudentName' and no accessible extension method 'StudentName' accepting a first argument of type 'IGrouping' could be found (are you missing a using directive or an assembly reference?)" 看到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
});
so the 2nd piece generate a design error 所以第二件产生设计错误
The equivalent Method syntax for your first query would be 第一个查询的等效方法语法是
var testS = ObjectsMisc.studentList
.GroupBy(s => s.StandardID)
.OrderBy(sg => sg.Key)
.Select(sg => new { sg.Key, sg})
However this does not select the StudentName
and Age
properties, but the whole student objects. 但是,这不会选择
StudentName
和Age
属性,而是选择整个学生对象。
If your students have a StudentName
and an Age
property and you want to select these grouped by StandardId
, it would be the following method syntax 如果您的学生具有
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.