0

I need to create a Distinct class for a LINQ query. Let's say the Department DTO class looks like this:

public class Department
{
    public int ID {get; set;} //primary key
    public string Name {get; set;}
    public string Address {get; set;}
}

and I need to query by distinct department names (not IDs). Will my GetHashCode look like

public int GetHashCode(Department record)
{
    return record.NAME.GetHashCode();
}

or will it look like

public int GetHashCode(Department record)
{
    return record.ID.GetHashCode();
}
joym8
  • 4,014
  • 3
  • 50
  • 93
  • @T.Rahgooy no, it's not – joym8 Aug 17 '15 at 16:18
  • possible duplicate of [What is the best algorithm for an overridden System.Object.GetHashCode?](http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode) – Medeni Baykal Aug 17 '15 at 16:30
  • If you are going by distinct names why do you think you need `ID` involved at all? Also are you performing this distinct on a `IQueryable` or a `IEnumerable`? If you are working with queryables (Like you are using Entity Framework or similar) you can't use IEqualityComparer. – Scott Chamberlain Aug 17 '15 at 17:40
  • @ScottChamberlain Well, I'm not sure whether I should use ID or not because I don't know how `GetHashCode` will be used. I've used similar Distincts with EF and it has been working fine. This one was a `IQueryable` – joym8 Aug 17 '15 at 19:14
  • Neither should be used as hash codes should not be computed from mutable properties. – Enigmativity Sep 07 '17 at 00:27

0 Answers0