0

I have a LINQ similar to this:

var list = (from g in myPreBuiltQuery
            where g.Address != null
            orderby g.Schools.SchoolName
            select new ResultFindSummary
            {
               // fill some fields for this class
            }).Take(100).Distinct().ToArray();

But still it is returning extra duplicate results.

Crono
  • 10,211
  • 6
  • 43
  • 75

4 Answers4

4

The problem is that you're creating 100 different instances of a custom type (ResultFindSummary), and that instances of a custom type are only considered equal when they reference the same object.

The solution is to override the Equals() and GetHashCode() methods in the ResultFindSummary class.

Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
3

Distinct uses an IEqualityComparer on items in memory. Now you are making a distinction on an sql query which is probably translated wrongly. (You can inspect that with the SQL profiler).

Two possible solutions => use groupby in combination with a first. If you want to work on the sql directly.

Or use the distinct after you converted your result set to memory (using .ToList()) and implement the IEqualityComparer on the SomeClass.

woutervs
  • 1,500
  • 12
  • 28
2

Have you implemented the Equals method in your ResultFindSummary class ?

Here is a topic from MSDN on how to Distinct() function works : http://msdn.microsoft.com/en-us/library/bb348436(v=vs.110).aspx

gretro
  • 1,934
  • 15
  • 25
2

You are trying to do a Distinct on a ResultFindSummary object. To use Distinct on an object you would need to use the Distinct override (http://msdn.microsoft.com/en-us/library/bb338049%28v=vs.110%29.aspx) that provides a class that implements the IEqualityComparer interface...

http://msdn.microsoft.com/en-us/library/ms132151%28v=vs.110%29.aspx

xspydr
  • 3,030
  • 3
  • 31
  • 49