【发布时间】:2019-07-17 21:49:03
【问题描述】:
我一直在这里查看其他线程,以了解如何在 linq 中进行 GroupBy。我正在遵循对其他人有用的 EXACT 语法,但是它不起作用。
这是查询:
var results = from p in pending
group p by p.ContactID into g
let amount = g.Sum(s => s.Amount)
select new PaymentItemModel
{
ContactID = g.ContactID, // <--- Error here
Amount = amount
};
pending 是一个List<T>,其中包含ContactID 和Amount 等列,但我在此查询中只关心这两列。
问题是,在select new 中,g. 不会给我原始列表pending 中的任何列。当我尝试时,我得到:
IGrouping
<int, LeadPurchases>不包含 ContactID 的定义,也没有扩展方法 blah blah blah...
这是我要模拟的 SQL:
SELECT
lp.PurchasedFromContactID,
SUM (lp.Amount)
FROM
LeadPurchases lp
GROUP BY
lp.PurchasedFromContactID
【问题讨论】:
-
你会想要
g.Key.ContactID -
这让我明白了:int 不包含 ContactID 的定义
-
抱歉 - 我的想法不正确。它应该只是
ContactID = g.Key,因为您只是按单个值分组