如何显示数组值在数组中出现的次数?

3

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

假设我有一个包含8个值的数组,数组={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个回答

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 的组中有多少项(如果您还记得,那是原始值)。


现在这才是真正的棒极了! - Aditi
1
很好,能够向提问者解释一下你在这里做什么会更好……不过回答很好。 - Th0rndike
@MarcGravell 很棒! :) - Th0rndike
谢谢,是的,回答真的很快而且正确:o)非常感谢。我还没有学习Linq,但这是很棒的东西。 - Momo
根据您的解决方案,一个有趣的琐事问题:C#不允许在同一块中使用相同的简单名称具有两个不同的含义。那么为什么您可以将“grp”既用作循环变量又用作lambda的形式参数是合法的呢? - Eric Lippert
@Erip 我记得你过去在博客上写过这个 - lambda 中的 grp 范围是被隔离到 lambda 中的,对吧? - Marc Gravell

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

Here is a DEMO.


0

你可以通过 Enumerable.GroupBy 来处理这个问题。我建议查看 C# LINQ samples 中关于 Count 和 GroupBy 的部分以获取指导。

在你的情况下,代码可能如下:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接