fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var c = new Counter<int>();
  9. c.Increment(1);
  10. c.Increment(2);
  11. c.Increment(1);
  12. c.Increment(1);
  13. foreach (var kvp in c) {
  14. Console.WriteLine(kvp);
  15. }
  16. }
  17. public class Counter<T> : IEnumerable<KeyValuePair<T, int>> {
  18. private Dictionary<T, int> counts = new Dictionary<T, int>();
  19.  
  20. public void Increment(T key) {
  21. int current;
  22. bool exists = counts.TryGetValue(key, out current);
  23. if (exists) {
  24. counts[key]++;
  25. }
  26. else {
  27. counts[key] = 1;
  28. }
  29. }
  30.  
  31. IEnumerator<KeyValuePair<T, int>>
  32. IEnumerable<KeyValuePair<T, int>>.GetEnumerator() {
  33. return ((IEnumerable<KeyValuePair<T, int>>) counts).GetEnumerator();
  34. }
  35.  
  36. System.Collections.IEnumerator
  37. System.Collections.IEnumerable.GetEnumerator() {
  38. return counts.GetEnumerator();
  39. }
  40. }
  41. }
Success #stdin #stdout 0.05s 34032KB
stdin
Standard input is empty
stdout
[1, 3]
[2, 1]