LINQ GroupBy Anonymous Type

走远了吗. 提交于 2020-01-13 11:43:10

问题


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?


回答1:


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.




回答2:


http://msdn.microsoft.com/en-us/library/bb397696.aspx

This link explains that GetHashCode and Equals are overridden.




回答3:


It doesn't work on OrderBy because the new object does not implement IComparable.



来源:https://stackoverflow.com/questions/9793416/linq-groupby-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!