How to group by on a reference type property in linq?
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.
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
精彩评论