簡體   English   中英

在方法語法中選擇C# - 返回匿名對象的集合

[英]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})

但是,這不會選擇StudentNameAge屬性,而是選擇整個學生對象。

如果您的學生具有StudentNameAge屬性,並且您想要選擇按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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM