1

I'm using C# / Entity Framework and trying to use Distinct() with just one property, but I could not find the correct syntax.

What I have:

context
.Orders
.Select(o => o.User)
.Distinct();

The final query is doing a distinct with the entire User object:

SELECT 
    [Distinct1].[ID] AS [ID], 
    [Distinct1].[Name] AS [Name], 
    [Distinct1].[Email] AS [Email], 
    (...)

What I need is to distinct just using one property, like Name. The final query would be something like:

SELECT 
    [ID], 
    [Distinct1].[Name] AS [Name], 
    [Email], 
    (...)

If I use ToList() before Distinct(), I can use a EqualityComparer inside Distinct(), but I'm trying to avoid it since I'm having performance issues, since it is loading a high load of information into memory instead of filtering in the database.

Ricardo
  • 448
  • 4
  • 7
  • 19
  • Check MoreLinq https://code.google.com/p/morelinq/ , ( DistinctBy : https://code.google.com/p/morelinq/wiki/OperatorsOverview ) – Mate Feb 11 '15 at 01:44

1 Answers1

0

Try using a comparer:

public class UserComparer : IEqualityComparer<User>
{
    public bool Equals(User x, User y)
    {
        return (x.Name == y.Name);
    }

    public int GetHashCode(User user)
    {
        return user.GetHashCode();
    }
}

context.Orders.Select(o => o.User).Distinct(new UserComparer());

My guess is entity framework should base it on the Name and not the whole object.

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29