2

I have a class like this:

public class Order
{
  public int Id;
  public Person SalesPerson;
  ...
}
public class Person
{
  public int Id;
  public string Name;
  ...
}

I writed a query in LINQ like this:

Order[] orders = GetAllOrders();
var myResult = select o from orders
               group o by o.SalesPerson.Id into oGroup
               select new {SalesPersonId = oGroup.Key, Order = oGroup}

It work correctly. But I will group on SalesPerson object not on SalesPersonId. When I group by SalesPerson its not group correctly even I impelement IEquatable<Person> interface but it doesn't work still. what should I do?

tanx for your help.

Amir Borzoei
  • 670
  • 2
  • 9
  • 30
  • 7
    What's your .Equals() and .GetHashCode() implementation on Person? You should always override both if they mean anything to you. Also - accepting questions helps motivating people. – Benjamin Podszun Feb 20 '10 at 08:38

1 Answers1

4

oh yes, Benjamin Podszun is right. I should override GetHashCode() method too. so my class is like this:

public class Person : IEquatable<Person>
{ 
  public int Id; 
  public string Name; 
  ... 

  public bool Equals(Person other)
  {
    return other == null ? false : this.Id == other.Id;
  }
  public override int GetHashCode()
  {
    return this.Id.GetHashCode();
  }
}

thank you

Amir Borzoei
  • 670
  • 2
  • 9
  • 30