我在LINQ中有这个查询,其中query
是来自表LeadSales
的预定义IQueryable ...
var results = from q in query
select new LeadBuyersByStateItem {
ContactID = q.SoldToContactID,
FirstName = q.Contact.FirstName,
LastName = q.Contact.LastName
};
它工作正常,但我需要稍微调整一下。我在SQL中也有这个:
SELECT
SoldToContactID,
COUNT (SoldToContactID) AS Count
FROM
LeadSales
GROUP BY
SoldToContactID
按预期方式返回此数据集:
所以现在,我需要将LINQ查询转换为GROUP BY,并包含Count,当然还要保存导航,以便我可以访问FirstName和LastName。
我遇到LINQ语法问题......
var results = from q in query
group q by q.SoldToContactID into g
select new LeadBuyersByStateItem {
ContactID = ?.SoldToContactID,
FirstName = ?.Contact.FirstName,
LastName = ?.Contact.LastName
ContactCount = ????
};
只是我们......
public class LeadBuyersByStateItem
{
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ContactCount { get; set; }
}
答案 0 :(得分:3)
我认为这就是你要找的东西:
var results = from q in query
group q by new {q.SoldToContactID,
FirstName=q.Contact.FirstName,
LastName=q.Contact.LastName} into g
select new LeadBuyersByStateItem {
ContactID = g.Key.SoldToContactID,
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
ContactCount = g.Count()
};
您需要使用匿名类型
按多个列进行分组