Group the collection using a function which returns the key. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Group the collection using a function which returns the key.

Demo Code

// Permission is hereby granted, free of charge, to any person
using System.Globalization;
using System.Linq;
using System.Collections;
using System.Text;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;// w w  w .  j  a va  2s  .co m

public class Main{
        /// <summary>
    /// Group the collection using a function which returns the key.
    /// </summary>
    /// <param name="source">The source collection to group.</param>
    /// <param name="keySelector">The key selector.</param>
    /// <returns>A Dictionary with each key relating to a list of objects in a list grouped under it.</returns>
    public static Dictionary<K, List<V>> GroupBy<K, V>(ICollection<V> source, Func<V, K> keySelector)
    {
      if (keySelector == null)
        throw new ArgumentNullException("keySelector");

      Dictionary<K, List<V>> groupedValues = new Dictionary<K, List<V>>();

      foreach (V value in source)
      {
        // using delegate to get the value's key
        K key = keySelector(value);
        List<V> groupedValueList;

        // add a list for grouped values if the key is not already in Dictionary
        if (!groupedValues.TryGetValue(key, out groupedValueList))
        {
          groupedValueList = new List<V>();
          groupedValues.Add(key, groupedValueList);
        }

        groupedValueList.Add(value);
      }

      return groupedValues;
    }
}

Related Tutorials