user482375
user482375

Reputation:

Selecting Distinct using LINQ with CRM

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?

Upvotes: 2

Views: 2122

Answers (2)

code4life
code4life

Reputation: 15794

Use a specified IEqualityComparer<T>: http://msdn.microsoft.com/en-us/library/bb356803

One other thing, I'm not sure if anonymous classes support the IEqualityComparer<T> implementations.

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64507

The Distinct call without an explicit comparer simply uses the default equality comparer, which in the case of anonymous types boils down to Object.Equals. This is overridden in anonymous types to be equal if all properties of the type are equal. In this case it will check the AccountId and Account properties.

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.

Upvotes: 1

Related Questions