I am trying to Select Distinct set using a LINQ to CRM query and it continues to return dupilicate records. The query I am using is:
var linqQuery = (from r in gServiceContext.CreateQuery("opportunity")
join c in gServiceContext.CreateQuery("account") on ((EntityReference)r["accountid"]).Id equals c["accountid"]
join u in gServiceContext.CreateQuery("systemuser") on ((EntityReference)r["ownerid"]).Id equals u["systemuserid"]
where (r["statuscode"].Equals("100000004") || r["statuscode"].Equals("100000003")) && r["statecode"].Equals("Open")
where u["internalemailaddress"].Equals(_currentUser.Email)
select new
{
AccountId = !c.Contains("accountid") ? string.Empty : c["accountid"],
Account = !c.Contains("name") ? string.Empty : c["name"]
}).Distinct();
Am I missing something to make .Distinct() work? Or is there a better way to do it?
The
Distinctcall without an explicit comparer simply uses the default equality comparer, which in the case of anonymous types boils down toObject.Equals. This is overridden in anonymous types to be equal if all properties of the type are equal. In this case it will check theAccountIdandAccountproperties.I suspect this is working and that the values are different in terms of case (as strings compare case-sensitive by default) or they are in fact distinct and you just can’t see it.
Luckily, it has nothing to do with the CRM-specific Linq provider.