Created
March 2, 2017 22:01
-
-
Save luanshixia/1429810f236254844dd5081dd47004c5 to your computer and use it in GitHub Desktop.
C# Counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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