The problem here is that OnlineAccountCategory is a reference type property (and not a string or something like that). Grouping by reference types uses method GetHashCode()
of a class by which the grouping is occuring.
And the key thing is if the GetHashCode()
method throws an exception (for instance, if it relies on working with a property of our object which is null
) the GroupBy()
method won't fail. It will just return a GroupedEnumerable
that contains an exception inside for some reason.
// Trying to add this to watch:
Items.First().OnlineAccountCategory.GetHashCode()
// Receiving:
'Items.First().OnlineAccountCategory.GetHashCode()' threw an exception of type
'System.NullReferenceException' int {System.NullReferenceException}
Hence, when we are trying to access an element of the collection, it falls with NullReferenceException
.
To solve this we have two approaches:
Override the GetHashCode
method of our OnlineAccountCategory
so it will not fail on incorrect values and instead of throwing an
exception will return something like 0.
Group by some value type instead (for instance,
OnlineAccountCategory.Id
). It will group by it and hence won't
fail.
Update:
The problem will occur only when the GetHashCode()
method was already implemented incorrectly (which was implemented in the base class in my case). The default reference comparer will work with that as expected.
The GetHashCode()
method for me looks like this:
public override int GetHashCode()
{
// Title is a string
return Title != null ? Title.GetHashCode() : 0;
}
So I don't really understand why does it break with a NullReferenceException here.