【问题标题】:Select a field that is not in Group By clause in LINQ在 LINQ 中选择不在 Group By 子句中的字段
【发布时间】:2011-12-28 20:15:06
【问题描述】:

谁能帮我 “如何在 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 中拥有该字段,因为我会得到错误的结果。 谢谢!

【问题讨论】:

  • 每一组有很多DateField值,你需要哪一个?
  • 如果在 group by 子句中包含 DateField 会给出错误的结果,那么似乎每个分组的元素都有不同的 DateField 值。在这种情况下,不清楚 哪些 您希望将这些值包含在结果序列的元素中。
  • 当您不想在分组中使用 DateField 时,意味着可能在一个分组中存在两个或多个 DateField ,那么如何通过两个或多个 DateField 选择一个组?

标签: c# .net sql-server linq


【解决方案1】:

我认为您需要在分组之前选择两个表成员,以便您可以从两者中选择数据。我做了一个 join 而不是你的 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);

【讨论】:

    【解决方案2】:

    也许这会起作用?

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

    【讨论】:

    • 这也将按日期值分组。我相信这不是故意的
    • @UfukHacıoğulları 我同意你的看法
    猜你喜欢
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2018-03-23
    相关资源
    最近更新 更多