簡體   English   中英

選擇LINQ中不在Group By子句中的字段

[英]Select a field that is not in Group By clause in LINQ

任何人都可以幫助我“如何選擇LINQ中不在Group By子句中的字段”

  var ReportData = 
      from a in context.Table1
      from b in context.Table2
      where a.personelID == b.ID
      && a.DateField.Value.Year == 2011
      group a by new { a.personelID, b.Name, b.Surname} into grouping
      select new
      {
           // grouping.Key.DateField,
          Name= grouping.Key.Name,
          Surname= grouping.Key.Surname,
          PagaBruto =  grouping.Sum(i => i.Bruto)),
      };

我無法選擇Table1中的 "DateField"字段,我不想在Group By包含此字段,因為我會得到錯誤的結果。 謝謝!

我認為您需要在分組之前選擇兩個表成員,以便從兩者中選擇數據。 我做了一個連接,而不是你的where子句。

(from a in context.Table1
 join b in context.Table2 on a.PersonalID equals b.ID
 select new { A=a, B=b } into joined
 group joined by new { joined.A.PersonalID, joined.B.Name, joined.B.Surname } into grouped
 select grouped.Select(g => new { 
                                    DateField= g.A.Datefield,
                                    Name = g.B.Name,
                                    Surname = g.B.Surname,
                                    PagaBruto = g.A.Sum(i => i.Bruto)
                                })).SelectMany(g => g);

也許這會奏效嗎?

  group a by new { a.personelID, b.Name, b.Surname, a.DateField} into grouping
  select new
  {
      DateField = grouping.Key.DateField,
      Name= grouping.Key.Name,
      Surname= grouping.Key.Surname,
      PagaBruto =  grouping.Sum(i => i.Bruto)),
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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