How to count the frequency of bundle of number using c#?

≡放荡痞女 提交于 2019-11-28 14:42:25

Well, you could do this manually using a Dictionary<int, int>:

var frequencies = new Dictionary<int, int>();
foreach (var item in data)
{
    int currentCount;
    // We don't care about the return value here, as if it's false that'll
    // leave currentCount as 0, which is what we want
    frequencies.TryGetValue(item, out currentCount);
    frequencies[item] = currentCount + 1;
}

A simpler but less efficient approach would be to use LINQ:

var frequencies = data.ToLookup(x => x) // Or use GroupBy. Equivalent here...
                      .Select(x => new { Value = x.Key, Count = x.Count() })
                      .ToList();
foreach (var frequency in frequencies)
{
    Console.WriteLine("{0} - {1}", frequency.Value, frequency.Count);
}

Assuming you have a list of numbers:

var numbers = new List<int>{ 1, 2, 3, 4, 1, 2, 2, 3 };

Then we can use Linq to achieve what you want:

var frequencies = 
    numbers.GroupBy( n => n ).Select( n => new { Value=n.Key, Count=n.Count() } );

foreach (var f in frequencies)
{
    Debug.WriteLine(string.Format("Value={0}, Frequency={1}", f.Value, f.Count));
}

I would put them all into a list then use a group by clause to group them ie

        List<int> numbers = new List<int> { 1, 2, 2, 3, 5, 6, 2, 1, 4, 4 };
        foreach (var group in numbers.GroupBy(n => n))
        {
            Console.WriteLine("{0} was found {1} times", group.Key, group.Count());
        }

I would use a dictionary of int and int: Dictionary and iterate through the numbers adding 1 as you go. some solutions use an array, but I prefer a dictionary this eliminates the need to manage the size of the array and is more memory efficient.

int[] someValues = { /* your numbers */ }
Dictionary<int,int> Counts = new Dictionary<int,int>();
foreach(int key in someValues)
{
    if ( !Counts.HasKey(key) ) Counts[ key ] = 0;
    Counts[key] = Counts[key] + 1;
}

then, you just iterate over the dictionary for your output:

foreach(KeyValuePair<int,int> kvp in Counts)
{
    Console.Write("{0} - {1}",kvp.Key,kvp.Value);
}

Homework assignment? We're not here to do homework assignments for you, but I will give you advice on what to do.

First, I would have a text reader so your input can be inputted. Then, parse each entry and add it into a dictionary. Then, iterate thru the dictionary to see how many times a specific entry occurs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!