IGrouping不包含定义

时间:2017-01-19 04:30:19

标签: c# linq

我一直在寻找其他线程,以了解如何在linq中进行GroupBy。我正在遵循对其他人有用的精确语法,但是,它不起作用。

以下是查询:

pending

List<T>是一个ContactID,其中包含Amountselect new等列,但这些是我唯一关心此查询的两个。

问题是,在g.内,pending不会给我原始列表中的任何列<int, LeadPurchases>。当我尝试时,我得到:

  

IGrouping SELECT lp.PurchasedFromContactID, SUM (lp.Amount) FROM LeadPurchases lp GROUP BY lp.PurchasedFromContactID 不包含ContactID的定义,也没有扩展方法blah blah blah ...

这是我试图模仿的SQL:

{{1}}

1 个答案:

答案 0 :(得分:4)

您在ContactID的基础上进行分组,因此它应该是结果的关键,因此您必须使用g.Key代替g.ContactID;这意味着查询应如下所示:

from p in pending
              group p by p.ContactID into g
              let amount = g.Sum(s => s.Amount)
              select new PaymentItemModel
              {
                  ContactID = g.Key,
                  Amount = amount
              };

更新:

如果要基于多个列执行分组,则GroupBy子句将如下所示:

group p by new
{
    p.ContactID,
    p.Field2,
    p.Field3
}into g
select new PaymentItemModel()
{
    ContactID = g.Key.ContactID,
    anotherField = g.Key.Field2,
    nextField = g.Key.Field3       
};
相关问题