c:for-each-group

<c:for-each-group
  name = identifier
  in = expression(IEnumerable<T> | IEnumerable)
  group-by? = lambda_expression
  group-size? = { integer } >
  <!-- Content: (c:sort*, sequence-constructor) -->
</c:for-each-group>

Processes a sequence of items in groups.

Category
instruction
Permitted parent elements
Any XCST element whose content model is sequence-constructor
Any literal result element

Attributes

group-by A lambda expression that computes the grouping key.
group-size The maximum number of items a group may have.
in The source of the items.
name The name of the group.

In addition to the attributes in the preceding table, there are a number of standard attributes that may appear on any XCST element.

Grouping By Key

If attributes group-by and group-size are both omitted, the items themselves are used as grouping key.

Example: Default Grouping
<c:for-each-group name='group' in='"hello".ToCharArray()' expand-text='yes'>
   <char count='{group.Count()}'>{group.Key}</char>
</c:for-each-group>

<!-- Outputs:

<char count="1">h</char>
<char count="1">e</char>
<char count="2">l</char>
<char count="1">o</char>
-->

Use the group-by attribute to specify a lambda expression that computes the grouping key.

Example: Specifying A Grouping Key
<c:for-each-group name='group' in='books' group-by='b => b.author' expand-text='yes'>
   <h2>{group.Key}</h2>
   <ul>
      <c:for-each name='book' in='group'>
         <li>...</li>
      </c:for-each>
   </ul>
</c:for-each-group>

When grouping by key, the group variable (declared by the name attribute) has the compile type IGrouping<TKey, TSource>, where TKey is the type of the grouping key and TSource the type of the item.

Processing Items In Chunks Of A Fixed Size

Use the group-size attribute to create groups with the same number of items, except for the last group which may have less.

Example: Using group-size
<c:for-each-group name='row' in='addressBook' group-size='3'>
   <div class='row'>
      <c:for-each name='address' in='row'>
         <div class='col-sm-4'>
            <address>
               ...
            </address>
         </div>
      </c:for-each>
   </div>
</c:for-each-group>

When using the group-size attribute, the group variable has the compile type IList<TSource>, where TSource is the type of the item.

Error Conditions

It is a compilation error if both attributes group-by and group-size are present.

See Also