Using Group in LINQ Query
I am using the LINQ to CRM provider.
I am querying the information then I am using LINQ to query the LINQ to CRM query so I can use GroupBy, since the LINQ to CRM provider does not support it. This is what I have so far.
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()
});
But I also want to be able to query the other variables that are in linqQuery
from linqQuery2
.
So I would want something like:
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
select new
{
OwnerName = myGroup.OwnerName,
OrderCount = myGroup.Count()
});
Is this possible to do?
Assuming the OwnerNames will be identical for all the items in the group then you could do something like:
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerId into myGroup
select new
{
OwnerName = myGroup.First().OwnerName,
OrderCount = myGroup.Count()
});
Edit:
If you want to use the first item multiple times, I'd suggest you use the 'let' operator:
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()
});
Try
var linqQuery2 = (from f in linqQuery.ToList()
group f by f.OwnerName
into myGroup
select new
{
OwnerName = myGroup.Key,
OwnerCount = myGroup.Count()
});
Alternately:
var linqQuery2 = linqQuery.ToList()
.GroupBy(f => f.OwnerName)
.Select(myGroup => new
{
OwnerName = myGroup.Key,
OwnerCount = myGroup.Count()
});
精彩评论