Skip to content

Instantly share code, notes, and snippets.

@luanshixia
Created March 2, 2017 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luanshixia/1429810f236254844dd5081dd47004c5 to your computer and use it in GitHub Desktop.
Save luanshixia/1429810f236254844dd5081dd47004c5 to your computer and use it in GitHub Desktop.
C# Counter
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Counts numbers of unique elements in a collection.
/// </summary>
/// <typeparam name="TElement">Type of elements.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <returns>A dictionary representing the counting result.</returns>
public static IDictionary<TElement, int> CountElements<TElement>(this IEnumerable<TElement> collection, IEqualityComparer<TElement> equalityComparer)
{
return collection
.GroupBy(element => element, equalityComparer)
.ToDictionary(group => group.Key, group => group.Count());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment