Partitions elements of the target collection into sub-groups based on the specified key generating function, and returns a dictionary of the generated keys, where each value is a list of the items that produced that key. Items appear in the sub-lists in the order in which they were enumerated from the target. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

Partitions elements of the target collection into sub-groups based on the specified key generating function, and returns a dictionary of the generated keys, where each value is a list of the items that produced that key. Items appear in the sub-lists in the order in which they were enumerated from the target.

Demo Code

// All rights reserved.
using System.Collections.Generic;
using System.Collections;
using System;/*from   www .jav  a 2 s  .  com*/

public class Main{
        /// <summary>
      /// Partitions elements of the target collection into sub-groups based on the specified key generating function,
      /// and returns a dictionary of the generated keys, where each value is a list of the items that produced that key.
      /// Items appear in the sub-lists in the order in which they were enumerated from the target.
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <typeparam name="K"></typeparam>
      /// <param name="target"></param>
      /// <param name="keyFunc"></param>
      /// <returns></returns>
      public static Dictionary<K, List<T>> GroupBy<T, K>(IEnumerable<T> target, Converter<T, K> keyFunc)
      {
         var results = new Dictionary<K, List<T>>();
         foreach (var item in target)
         {
            var key = keyFunc(item);
            List<T> group;
            if (!results.TryGetValue(key, out group))
            {
               results[key] = group = new List<T>();
            }
            group.Add(item);
         }
         return results;
      }
}

Related Tutorials