Anonymous types can be used here to group across multiple fields, because GroupBy uses the default GroupBy .
By default, equality mapping for each anonymous type property is used for equality mapping for anonymous types.
So, for the first anonymous type, two instances are equal if both Department and both Gender are equal (according to their default equality mappers).
You can imagine that an anonymous type looks something like this:
public class AnonymousType1 { public int Department { get; set; } // I don't know your department type public int Gender { get; set; } // neither your gender type public int GetHashCode() { return Department.GetHashCode() ^ Gender.GetHashCode(); } public bool Equals(AnonymousType1 other) { if (ReferenceEquals(other, null)) return false; return Department == other.Department && Gender == other.Gender; } }
The second question is also simple: the compiler uses property names ( Department from x.Department and Gender from x.Gender ) as property names of an anonymous type.
So,
var anon = new { employee.Department, employee.Gender }
creates a type with the Department property and the Gender property.
Of course, this can only work with existing properties / names, and not with constant values ββsuch as
var anon = new {1,2};
RenΓ© vogt
source share