3

我有一个包含重复值的数组。我需要显示在数组中找到每个值的次数。

假设我有一个包含 8 个值的数组,array = {1,2,3,1,1,2,6,7} 我需要输出为:

1 was found 3 times
2 was found 2 times
3 was found 1 time
6 was found 1 time
7 was found 1 time

这是我的代码。现在我将数组中的每个值保存到一个变量中,然后循环遍历数组以检查该值是否存在,然后将其打印出来。

 int[] nums = { 2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32 };
            for (int i = 0; i < nums.Length; i++)
            {
                int s = nums[i];
                for (int j = 0; j < nums.Length; j++)
                {
                    if (s == nums[j])
                    {
                        Console.WriteLine(s);
                    }
                }

            }

提前致谢

4

4 回答 4

13
foreach(var grp in nums.GroupBy(x => x).OrderBy(grp => grp.Key)) {
    Console.WriteLine("{0} was found {1} times", grp.Key, grp.Count());
}

使用数字本身作为键(通过)将GroupBy所有值分组x => x。对于每个唯一值,我们将有一个不同的组,其中包含一个或多个值。这OrderBy确保我们按键顺序(通过grp => grp.Key)报告组。最后,Count告诉我们有多少项目在由Key(原始值,如果你记得的话)标识的组中。

于 2013-03-06T11:47:32.100 回答
2

分组.Key和排序.Count后如何使用

foreach(var g in nums.GroupBy(x => x).OrderBy(g => g.Key))
{
    Console.WriteLine("{0} was found {1} times", g.Key, g.Count());
}

这是一个DEMO.

于 2013-03-06T11:48:41.187 回答
0

您可以通过Enumerable.GroupBy处理此问题。我建议查看有关 Count 和 GroupBy 的C# LINQ 示例部分以获取指导。

在您的情况下,这可以是:

int[] values = new []{2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32};

var groups = values.GroupBy(v => v);
foreach(var group in groups)
    Console.WriteLine("{0} was found {1} times", group.Key, group.Count());
于 2013-03-06T11:51:18.187 回答
0

您是否正在使用阵列进行纯教育?C#Collections提供了许多方便的功能来解决此类问题。System.Collections.Dictionary提供您正在寻找的功能。添加一个项目,如果它不存在并做出反应,当一个键已经被添​​加时。

using System.Collections.Generic;

Dictionary<int,int> dic = new Dictionary<int, int>();
if(!dic.Keys.Contains(key))
   //add key and value
else 
  //get key and add value

请参阅MSDN

于 2013-03-06T11:54:05.140 回答