-1

I have an array, and I want to count the number of instances it appears.

Example input:

int[] a = new int[]{1,1,1,2,3,4,4};

output:

1  3
2  1
3  1
4  2

So far I am able to get the distinct but can't get the count.

public static void arrayfrequency(int[] a)
{
    //store the distinct list
    var GetDistinct = a.Distinct().ToArray();

    foreach (int index in GetDistinct)
    {
        Console.WriteLine(index);
    }
}
cookiemonster
  • 368
  • 1
  • 8
  • 22

2 Answers2

7

You can use GroupBy and Count to achieve it using Linq.

int[] a=new int[]{1,1,1,2,3,4,4};
foreach(var item in a.GroupBy(x=>x))
{
    Console.WriteLine($"{item.Key} {item.Count()}");
}

The GroupBy would group all the similar values together, while the Count could return the number of items in each group, effectively the count of duplicates.

Understanding it step by step, following is a pictorial representation of GroupBy

enter image description here

Now, all you need to do is Count the Groups for each key in your loop for display.

Output for sample input

1 3
2 1
3 1
4 2
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • 1
    Not my downvote, but the question was poorly written, such that the line breaks were lost. That could be it. Also, there are some who tend to downvote cryptic linq answers. Better practice when there are indications you're dealing with a newbie is to also provide an answer with more traditional code... but again: not my downvote, and I've also written answers like this. – Joel Coehoorn Jan 27 '19 at 05:02
  • Thanks @JoelCoehoorn , I think i would add some explanation. It is weird when someone downvotes and never explains why. One can never learn from that. – Anu Viswan Jan 27 '19 at 05:04
1

You can use a Dictionary:

public static void arrayfrequency(int[] a)
{
    var result = new Dictionary<int,int>();
    foreach (int item in a)
    {
        if (!result.ContainsKey(item))
        {
            result.Add(item, 1);
        }
        else
        { 
            result[item]++;
        }
    }

    foreach(var key in result.Keys)
    {
        Console.WriteLine("{0} {1}", key, result[key]);
    }
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794