IGrouping<TKey,TElement>.Key Property

Definition

Gets the key of the IGrouping<TKey,TElement>.

C#
public TKey Key { get; }

Property Value

TKey

The key of the IGrouping<TKey,TElement>.

Examples

The following example demonstrates how to use the Key property to label each IGrouping<TKey,TElement> object in a sequence of IGrouping<TKey,TElement> objects. The GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) method is used to obtain a sequence of IGrouping<TKey,TElement> objects. The foreach in Visual C# or For Each in Visual Basic loop then iterates through each IGrouping<TKey,TElement> object, outputting its key and the number of values it contains.

C#
// Get a sequence of IGrouping objects.
IEnumerable<IGrouping<System.Reflection.MemberTypes, System.Reflection.MemberInfo>> memberQuery =
    typeof(String).GetMembers().
    GroupBy(member => member.MemberType);

// Output the key of each IGrouping object and the count of values.
foreach (IGrouping<System.Reflection.MemberTypes, System.Reflection.MemberInfo> group in memberQuery)
    Console.WriteLine("(Key) {0} (Member count) {1}", group.Key, group.Count());

// The output is similar to:
// (Key) Method (Member count) 113
// (Key) Constructor (Member count) 8
// (Key) Property (Member count) 2
// (Key) Field (Member count) 1

Remarks

The key of an IGrouping<TKey,TElement> represents the attribute that is common to each value in the IGrouping<TKey,TElement>.

Applies to

Produkt Verzie
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0