我正在使用LINQ to CRM提供商。
我正在查询信息,然后我使用LINQ查询LINQ to CRM查询,因此我可以使用GroupBy,因为LINQ to CRM提供程序不支持它。这是我到目前为止所做的。
var linqQuery = (from r in orgServiceContext.CreateQuery("opportunity")
join c in orgServiceContext.CreateQuery("contact") on
((EntityReference)r["new_contact"]).Id equals c["contactid"] into opp
from o in opp.DefaultIfEmpty()
select new
{
OpportunityId = !r.Contains("opportunityid")
? string.Empty : r["opportunityid"],
CustomerId = !r.Contains("customerid")
? string.Empty : ((EntityReference)r["customerid"]).Name,
OwnerId = !r.Contains("ownerid")
? string.Empty : ((EntityReference)r["ownerid"]).Id.ToString(),
OwnerName = !r.Contains("ownerid")
? string.Empty : ((EntityReference)r["ownerid"]).Name.ToString(),
Priority = !r.Contains("opportunityratingcode")
? string.Empty : r.FormattedValues["opportunityratingcode"],
ContactName = !r.Contains("new_contact")
? string.Empty : ((EntityReference)r["new_contact"]).Name,
// ...
// other properties
});
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
select new
{
OrderCount = myGroup.Count()
});
但我也希望能够从linqQuery
查询linqQuery2
中的其他变量。
所以我想要这样的东西:
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
select new
{
OwnerName = myGroup.OwnerName,
OrderCount = myGroup.Count()
});
这可能吗?
答案 0 :(得分:2)
假设OwnerNames对于组中的所有项目都是相同的,那么您可以执行以下操作:
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
select new
{
OwnerName = myGroup.First().OwnerName,
OrderCount = myGroup.Count()
});
修改强>
如果您想多次使用第一项,我建议您使用'let'运算符:
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
let first = myGroup.First()
select new
{
OwnerName = first.OwnerName,
OrderCount = myGroup.Count()
});
答案 1 :(得分:1)
尝试
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerName
into myGroup
select new
{
OwnerName = myGroup.Key,
OwnerCount = myGroup.Count()
});
可替换地:
var linqQuery2 = linqQuery.ToList()
.GroupBy(f => f.OwnerName)
.Select(myGroup => new
{
OwnerName = myGroup.Key,
OwnerCount = myGroup.Count()
});