如何使用C#计算数字捆绑的频率? [英] How to count the frequency of bundle of number using c#?

查看:58
本文介绍了如何使用C#计算数字捆绑的频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我使用c#运行此程序吗?这个程序是要计算频率的数字,例如12出现10x。在此之前,我尝试将所有列表编号排成一条水平线。然后我比较相同的数字,然后计数++,但是直到知道我无法获得输出为止。

Can somebody help me to run this program using c#. This program is to calculate the frequency of the number, for example 12 appear 10x. Before this I try to sort all list number in a horizontal line. Then I compare the same number, then count++, but until know I can’t get the output.

感谢您的帮助。

输入

46 31 46 9 25 12 45 33
25 12 12 12 28 36 38 28
25 12 12 9 36 38 36 36
12 9 36 12 12 25 28 34
36 36 9 12 16 25 28 44

46 31 46 9 25 12 45 33 25 12 12 12 28 36 38 28 25 12 12 9 36 38 36 36 12 9 36 12 12 25 28 34 36 36 9 12 16 25 28 44

输出

9 – 4
12 -10
16 – 1
25 – 5
28-4
31 – 1
33 – 1
34-1
36 – 7
38 – 2
44 – 1
45 – 1
46 – 2

9 – 4 12 -10 16 – 1 25 – 5 28 - 4 31 – 1 33 – 1 34 - 1 36 – 7 38 – 2 44 – 1 45 – 1 46 – 2

推荐答案

好吧,您可以使用 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;
}

一种更简单但效率较低的方法是使用LINQ:

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);
}

这篇关于如何使用C#计算数字捆绑的频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆