Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ GroupBy Anonymous Type

I am wondering why GroupBy works with anonymous types.

List<string> values = new List<string>();
values.GroupBy(s => new { Length = s.Length, Value = s })

Anonymous types do not implement any interfaces, so I am confused how this is working.

I assume that the algorithm is working by creating an instance of the anonymous type for each item in the source and using hashing to group the items together. However, no IEqualityComparer is provided to define how to generate a hash or whether two instances are equal. I would assume, then, that the Object.Equals and Object.GetHashCode methods would be the fallback, which rely on object identity.

So, how is it that this is working as expected? And yet it doesn't work in an OrderBy. Do anonymous types override Equals and GetHashCode? or does the underlying GroupBy algorithm do some magic I haven't thought of?

like image 908
Travis Parks Avatar asked Mar 20 '12 19:03

Travis Parks


1 Answers

As per the documentation, an anonymous type is a reference type:

From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

Therefore, it will be using the default implementation for those functions as implemented by System.Object (which at least for equality is based on referential equality).

EDIT: Actually, as per that same first doco link it says:

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

like image 157
Reddog Avatar answered Sep 29 '22 09:09

Reddog