Bagikan melalui


IGrouping<TKey, TElement>.Key Property

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

Syntax

'Declaration
ReadOnly Property Key As TKey
TKey Key { get; }

Property Value

Type: TKey
The key of the IGrouping<TKey, TElement>.

Remarks

The key of an IGrouping<TKey, TElement> represents the attribute that is common to each value in 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.

      ' Get a sequence of IGrouping objects.
      Dim memberQuery As  _
      IEnumerable(Of IGrouping(Of System.Reflection.MemberTypes, System.Reflection.MemberInfo)) = _
          Type.GetType("String").GetMembers(). _
          GroupBy(Function(member) member.MemberType)

      ' Output the key of each IGrouping object and the count of values.
      For Each group As  _
      IGrouping(Of System.Reflection.MemberTypes, System.Reflection.MemberInfo) In memberQuery
         outputBlock.Text &= String.Format("(Key) {0} (Member count) {1}", _
                                           group.Key, group.Count()) & vbCrLf
      Next

      ' 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

      // 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)
         outputBlock.Text += String.Format("(Key) {0} (Member count) {1}", group.Key, group.Count()) + "\n";

      // 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

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.