Search code examples
pythonc#.netdictionarycounter

Is there a .NET object in C# that mimics a Python Counter Class from Collection?


I have the docs here for the Counter Class in Python.

I have a Hash Set in C# that I generated from a List of string in C#. I have been using this code block to count the items.

foreach( var item in dict_of_dates.Values)
{
    foreach(var item2 in item)
    {
        if (item2 == set_1.ElementAt(0))
            count++;
        else if (item2 == set_1.ElementAt(1))
            count_1++;
        else if (item2 == set_1.ElementAt(2))
            count_2++;
        else if (item2 == set_1.ElementAt(3))
            count_3++;
        else if (item2 == set_1.ElementAt(4))
            count_4++;
        else if (!set_1.Contains(item2))
            count_5++;
    }
}

The issue with this code is that if I do not know the number of items that are going to be in my set. It would just require a increase in number of if elseif conditions and saving the count to the counter variables. I would like to avoid this seeing that it makes the code bulky in general. My general question is, is there a prebuilt counter class in C# possibly using lambdas and the hash set or do I have to create my own Counter Class?

I am trying to get a collection that has the following output:

{"a": 20, "b": 30, "c": 40}

This is so like that I can loop over the output and plot the keys and values.

I have read this question and it is in F#.

Question 1

Solution that worked:

var h = dict_of_dates.Values
    .SelectMany(x => x)
    .GroupBy(s => s)
    .ToDictionary(g => g.Key, g => g.Count());

foreach(var item in h)
{
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);
}

Solution

  • An approach using LINQ would be:

    using System;
    using System.Linq;
    using System.Collections.Generic;
                        
    public class Program
    {
        public static void Main()
        {
            var input = new List<string> {"a", "b", "c","a", "b", "c","a", "b", "c","a", "b","a", "b","a", "c"};
            var histogram = input.GroupBy(x => x).ToDictionary(g => g.Key, g=> g.Count());
        }
    }
    

    This creates a histogram of the elements of the list by grouping them by value and then counting the elements of each group.

    In Action : Fiddle