Search code examples
c#igrouping

Igrouping does not find the right key for custom class


I have a custom class that contains 3 fields:

public class Selector
{
    public long? SubTypeID {get;set;}
    public int TypeID { get; set; }
    public DateTime? ActionDate { get; set; }
}

IEnumerable<IGrouping<Selector, Log>> query = src.GroupBy(td => new Selector() 
    {SubTypeID = td.SubTypeID, ActionDate = td.ActionDate, TypeID = td.ActivityTypeID}, 
    td => td);

When I have two logs that contain ActionDate = 'Sept 9, 2013' and SubTypeID = 3, and TypeID = 1, any idea why it might not group the two logs? Do I need to implement a custom compare? What is actually missing here?

Thanks!


Solution

  • You have to override Equals and GetHashCode methods within your Selector class. Otherwise standard reference comparison is being performed, and that's why your items are not grouped together.

    You should also read Why is it important to override GetHashCode when Equals method is overridden?