I want to GroupBy multiple objects in a list of records and not simply multiple values.
I am having trouble getting grouping to work with reference type objects. I have a collection of objects that contain Room, Type, and DateTime. Room, Type, and DateTime all have properties associated with them. I've already added the IEquateable interface to the room and the type thinking that would be enough to with with group by.
var groups = collection
.Where(g => g.Stage == InventoryStage.StageA)
.GroupBy(g => new {g.BirthDate, g.Room, g.Type});
In order for this code to work i have to call our a specific property on these objects to group by. The problem with that is that i need the complex objects stored in the "Key" of the grouping so that i can access that groups specific information
var groups = collection
.Where(g => g.Stage == InventoryStage.StageA)
.GroupBy(g => new {
Birthday = g.BirthDate,
RoomName = g.Room.Name,
TypeName = g.Type.Name
});
I end up having to do ^ to get the grouping to work, however the groups lose the complicated object i wanted.
To accomplish this task, you can override Equals() and GetHashCode() methods for your classes:
public class Room {
public string Name;
public string Foo;
public override bool Equals(object obj)
{
Room other = obj as Room;
if (other == null) return false;
return this.Name == other.Name && this.Foo == other.Foo;
}
public override int GetHashCode()
{
return (Name.GetHashCode() ^ Foo.GetHashCode()).GetHashCode();
}
}
Take a look here for more complicated example