【问题标题】:Count the frequency of element of an array in C# [duplicate]在C#中计算数组元素的频率[重复]
【发布时间】:2019-06-14 18:17:32
【问题描述】:

我想用 C# 编写代码。

事实上,我想用 C# 编写一个程序,让程序接收一个数字列表,然后接收另一个数字,最后检查接收到的数字在给定列表中出现了多少次。

我从 GitHub 上搜索并获得了以下 C# 代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Array9a
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j,N,count;

            Console.WriteLine("Enter the Maximum Range for the Array");
            N = Convert.ToInt32(Console.ReadLine());
            string[] a = new string[N];
            int[] freq = new int[N];
            for (i = 0; i < N; i++)
            {
                a[i] = Console.ReadLine();
               freq[i] = -1;
            }
            for (i = 0; i < N; i++)
            {
                count = 1;
                for (j = i + 1; j < N; j++)
                {
                    if (a[i] == a[j])
                    {
                        count++;
                        freq[j] = 0;
                    }


                }
                if (freq[i] != 0)
                {
                    freq[i] = count;
                }

            }
            for (i = 0; i < N; i++)
             {
                 if (freq[i] != 1)
                {
                    Console.Write("{0}{1}", a[i], freq[i]);
                }
            }
            Console.ReadLine();
        }
    }
}

上述代码的输出是所有元素的频率。但我想修改代码,让程序接收一个数字,然后检查给定数字的频率。

最近我在学习 C#。提前致谢

【问题讨论】:

  • 那么您是否只想计算给定数字出现的次数?
  • @John 是的。只是程序计算给定数字出现的频率。
  • 您似乎希望您的程序计算所有数字?
  • 考虑将数据存储在 Dictionary&lt;int, int&gt; 而不是数组中。
  • @RoadRunner 你说得对。事实上,我想修改它,只计算给定数字的频率。

标签: c#


【解决方案1】:

这看起来很简单。

var result = freq.Count(x => x == theNumberToCheck);

【讨论】:

  • @mjwills 也许我的问题很简单。但是我想让程序接收一个数字列表,例如 [1,2,2,3,4,5,5,5],然后程序要求输入一个数字,例如 5,然后程序的输出是“数字 5 是 3 次”。如果可能,请修改代码并将其作为答案发布。谢谢
  • @user freq 是您的数字数组,theNumberToCheck 是您作为输入的数字(并转换为正确的数据类型,例如 int)。
【解决方案2】:

非常简单,例如可以使用 linq

        int frequency = 1;
        int[] arr = new int[] { 1, 4, 6, 7, 1, 2, 6 ,1};
        var res =arr.Count(x => x == frequency);
        Console.WriteLine(res);//print 3

【讨论】:

    【解决方案3】:

    获取每个数字的计数:

    var distinctValues = theList.Distinct().ToArray();
    
    for(int i = 0; i < distinctValues.Length; i++)
    {
      var cnt = theList.Count(e => e == distinctValues[i]);
      Console.WriteLine($"Element {distinctValues[i]}, count {cnt}");
    }
    

    【讨论】:

    • 或者只是var freqList = numbers.GroupBy(x =&gt; x) .Select(x =&gt; new { x.Key, count = x.Count() })的一组
    • @TheGeneral 这取决于想要什么结果:)
    猜你喜欢
    • 2020-07-10
    • 2014-03-01
    • 2021-07-28
    • 2015-02-05
    • 2013-11-27
    • 2021-12-04
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多