如何计算数组中数字的频率?

coo*_*ter 0 c#

我有一个数组,我想计算它出现的实例数.

输入示例:

int[] a = new int[]{1,1,1,2,3,4,4};
Run Code Online (Sandbox Code Playgroud)

输出:

1  3
2  1
3  1
4  2
Run Code Online (Sandbox Code Playgroud)

到目前为止,我能够获得独特但无法得到的数据.

public static void arrayfrequency(int[] a)
{
    //store the distinct list
    var GetDistinct = a.Distinct().ToArray();

    foreach (int index in GetDistinct)
    {
        Console.WriteLine(index);
    }
}
Run Code Online (Sandbox Code Playgroud)

Anu*_*wan 7

您可以使用GroupBy和Count来使用Linq实现它.

int[] a=new int[]{1,1,1,2,3,4,4};
foreach(var item in a.GroupBy(x=>x))
{
    Console.WriteLine($"{item.Key} {item.Count()}");
}
Run Code Online (Sandbox Code Playgroud)

GroupBy会将所有相似的值组合在一起,而Count可以返回每个组中的项目数,实际上是重复项的数量.

逐步理解它,以下是GroupBy的图形表示

在此输入图像描述

现在,您需要做的就是为循环中的每个键计数组以供显示.

样本输入的输出

1 3
2 1
3 1
4 2
Run Code Online (Sandbox Code Playgroud)