0
using System;
using System.Collections.Generic;

class MainClass {
  public static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}
  }

Is there a way I can make this code that counts the number of duplicate values in an array work for strings, I need it to output something like:

Donald - 2 James - 1

The numbers being the amount of times it has been repeated in the string

  • 1
    Why wouldn't this work for a string array? Build your string array and then just do `var dict = new Dictionary()` and let 'er rip. – JNevill Oct 11 '18 at 15:29
  • use ToArray method of string to populate your arrays, then do as before – Cato Oct 11 '18 at 15:32

1 Answers1

2

If I understand your problem, you can use Generics!

Your code on generics:

using System;
using System.Collections.Generic;

public class MainClass
{
    public static void Main(string[] args)
    {
        int[] array = {10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};
        var dict = CountOccurence<int>(array);
        foreach (var pair in dict)
            Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);

        string[] array2 = {"10","10", "toto"};
        var dict2 = CountOccurence<string>(array2);
        foreach (var pair in dict2)
            Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    }

    public static IDictionary<T, int> CountOccurence<T>(IEnumerable<T> array)
    {
        var dict = new Dictionary<T, int>();
        foreach (var value in array)
        {
            if (dict.ContainsKey(value))
                dict[value]++;
            else
                dict[value] = 1;
        }
        return dict;
    }
}

output

Value 10 occurred 2 times.
Value 5 occurred 3 times.
Value 2 occurred 2 times.
Value 3 occurred 1 times.
Value 4 occurred 1 times.
Value 6 occurred 1 times.
Value 7 occurred 1 times.
Value 8 occurred 1 times.
Value 9 occurred 1 times.
Value 11 occurred 1 times.
Value 12 occurred 2 times.
Value 10 occurred 2 times.
Value toto occurred 1 times.

Try it online!

Next step, with Linq:

public static IDictionary<T, int> CountOccurence<T>(IEnumerable<T> array)
{
    return array.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
}

Try it Online!

There is a SO thread about counting with linq: How to Count Duplicates in List with LINQ

aloisdg
  • 22,270
  • 6
  • 85
  • 105