【问题标题】:How to display how many time an array value is in the array?如何显示数组值在数组中的次数?
【发布时间】:2013-02-21 04:39:59
【问题描述】:

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

假设我有一个包含 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);
                    }
                }

            }

提前致谢

【问题讨论】:

    标签: c# arrays for-loop


    【解决方案1】:
    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 =&gt; x)。对于每个唯一值,我们将有一个不同的组,其中包含一个或多个值。 OrderBy 确保我们按密钥顺序报告组(通过grp =&gt; grp.Key)。最后,Count 告诉我们Key 标识的组中有多少项目(如果你记得的话,是原始值)。

    【讨论】:

    • 这就是我所说的真棒!
    • 很高兴向 OP 解释你在这里做什么......但是很好的答案。
    • @MarcGravell 非常好! :)
    • 谢谢,是的,答案非常快速且正确:o) 非常感谢。我仍然没有学习 Linq,但是很棒的东西..
    • 一个基于您的解决方案的有趣琐事问题:C# 不允许使用相同的简单名称在同一块中具有两种不同的含义。那么为什么将grp 用作循环变量和 lambda 的形参是合法的?
    【解决方案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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

        您是否正在使用数组进行纯教育? 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

        【讨论】:

          猜你喜欢
          • 2020-12-25
          • 1970-01-01
          • 2021-03-19
          • 2016-04-02
          • 2020-06-12
          • 2015-05-27
          • 1970-01-01
          • 2022-08-11
          • 1970-01-01
          相关资源
          最近更新 更多