LINQ to Objects : How to Group Elements (part 3) - Grouping by Composite Keys
Published 3 min readBy Programming4us Editorial Team
3. Grouping by Composite Keys (More Than One Value)
To
group using more than one value as the key (often referred to as a
composite key), you specify the grouping selector clause as an
anonymous type. Any number of key values can be
specified in this anonymous type, and any element that contains
identical values will dutifully be co-located in a group.
Listing 3 demonstrates the simplicity of specifying multiple key values in the group by expression. In this case, the LastName and the State
fields are used for grouping, placing all contacts with the same last
name from the same state in a group. The Console output from this
example is shown in Output 2.
Listing 3. Anonymous types can be used to group by more than one value (composite key)—see Output 2
Output 2.
It is not essential to use an anonymous type as the
grouping key selector to achieve multiple-property groups. A named type
containing all of the properties participating in the key can be used
for the same purpose, although the method is more complex because the
type being constructed in the projection needs a custom override of the
methods GetHashCode and Equals to force comparison by property values rather than reference equality. Listing 4 demonstrates the mechanics of creating a class that supports composite keys using the fields LastName and State. The results are identical to that shown in Output 2.
Listing 4. Creating a composite join key using a normal class type