質問

In Linq to Object (Enumerables)

How does the default comparer resolve the following?

//The following is essentially a select distinct
var x = from student in class
        group student by new {student.MajorId, student.GradeId} into performanceStudentGroup
        select  new {  performanceStudentGroup.Key.MajorId, performanceStudentGroup.Key.GradeId};

Obviously in order for the above to work, the framework has to compare 2 anonymous types to check if they belong in the same group.

How does it do that? How is it able to check for something more than the reference pointers?

How is that comparer different than the following code:

var y = (from student in class
        select  new {  student.MajorId, student.GradeId}).Distinct();
役に立ちましたか?

解決

Following the MSDN documentation on Anyonymous Types

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.

The anonymous type will be created and has an Equals() and GetHashCode() implementation based on the properties. If the properties will be the same, these these two methods will return the same result. I imagine there's some collection in the back that holds the different instances of the anonymous type.

他のヒント

When the compiler generates an anonymous type, it also generates Equals() and GetHashCode() methods to compare it by value. You can see this in a decompiler.

The default EqualityComparer doesn't know anything about anonymous types; it simply calls these methods.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top