Select a field that is not in the Group By clause in LINQ

advertisements

could anybody help me about "How to select a field that is not in Group By clause in LINQ"

  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)),
      };

I can't select the field "DateField" that is in Table1, I don't want to have this field in Group By, because I will get a wrong result. THANKS!


I think you need to select both table members before you group by so you can select data from both. I did a join instead of your where clause.

(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);