LINQ GroupBy anonymous type
I'm wondering why GroupBy works with anonymous types.
List<string> values = new List<string>();
values.GroupBy(s => new { Length = s.Length, Value = s })
Anonymous types don't implement any interfaces, so I'm confused how this works.
I assume the algorithm works by instantiating an anonymous type for each item in the source and using hashing to group the items together. However, no IEqualityComparer is provided to determine how to generate a hash or if the two instances are the same. I would imagine that the Object.Equals and Object.GetHashCode methods would fallback, which would rely on the object id.
So how does it work as expected? And yet it doesn't work in OrderBy. Do Anonymous Types Override Equals and GetHashCode? or does the basic GroupBy algorithm do some magic that I haven't thought of?
source to share
According to the documentation, anonymous type is a reference type :
From a common language runtime perspective, an anonymous type is no different from any other reference type.
Hence, it will use the default implementation for those functions implemented by System.Object (which is at least for equality based on referential equality ).
EDIT . In fact, according to the same first doco link, it reads:
Because the Equals and GetHashCode methods for anonymous types are defined in terms of the Equals and GetHashcode property methods, two instances of the same anonymous type are equal only if their properties are all equal.
source to share
http://msdn.microsoft.com/en-us/library/bb397696.aspx
This link explains that GetHashCode and Equals are overridden.
source to share