要返回数组中最先出现数字最多的数,你可以使用一个 Dictionary 来记录每个数字的出现次数,并遍历数组来更新该字典。然后,找到字典中出现次数最多的数字,并返回它。

以下是一个示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static int FindMostFrequentNumber(int[] array)
    {
        Dictionary<int, int> countDict = new Dictionary<int, int>();

        foreach (int num in array)
        {
            if (countDict.ContainsKey(num))
            {
                countDict[num]++;
            }
            else
            {
                countDict[num] = 1;
            }
        }

        int mostFrequentNumber = countDict.OrderByDescending(x => x.Value).First().Key;
        return mostFrequentNumber;
    }

    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5, 2, 3, 4, 2, 2 };
        int mostFrequentNumber = FindMostFrequentNumber(array);
        Console.WriteLine('最先出现数字最多的数是:' + mostFrequentNumber);
    }
}

在示例代码中,FindMostFrequentNumber 方法接收一个整数数组,并使用字典 countDict 来记录每个数字的出现次数。通过遍历数组,如果数字已经存在于字典中,则增加其计数器;否则,将其添加到字典并初始化计数器为 1。然后,通过使用 LINQ 的 OrderByDescending 方法对字典中的值进行排序,并返回出现次数最多的数字。

Main 方法中,我们创建一个示例数组并调用 FindMostFrequentNumber 方法来获取最先出现数字最多的数,并将结果输出到控制台。

希望这个示例对你有所帮助!如果你还有其他问题,请随时提问。

C# 查找数组中最先出现次数最多的数字

原文地址: http://www.cveoy.top/t/topic/S8x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录