I have a list that i want to group based on properties on an object. But it seems when i output the grouped list it groups on every property in the object, even if i dont assign them any values. Since the default values should be the same for the unassigned values they should be grouped together, right?
I know i can solve this by using anonymous types ( new { x.SentDate.Year } ) and stuff, but the idea is to pass a GroupBy function as a parameter in PopulateMessages method for the sake of being more dynamic.
public void PopulateMessages()
{
List<Message> Messages = new DataRepository().GetMessages();
Func<Message, GroupProperties> func = x => new GroupProperties
{
Year = x.SentDate.Year
};
IEnumerable<IGrouping<GroupProperties, Message>> GroupedMessages = Messages.OrderByDescending( x => x.SentDate )
.GroupBy( func )
.ToList();
}
public class GroupProperties
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
I’d be surprised if you found your current code was grouping at all. Your current grouping key type is a class which doesn’t override
EqualsorGetHashCode, which means you’ll basically get reference equality. Every instance ofGroupPropertiesis non-equal to every other instance, and as you create a new instance for eachMessage, there’ll be no grouping.You need to override those methods appropriately (ideally implement
IEquatable<GroupProperties>) and then grouping will work. You shouldn’t need to care about which properties have been set, so long as your key extraction function always sets a consistent set of them.