we create a string List from a string array. Notice how there are some values, like "bird," that occur more than once in the string array.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Compute frequencies for this data.
string[] values = {
"bird",
"cat",
"bird",
"dog",
"bird",
"man",
"frog",
"cat" };
// Get a list.
List<string> valuesList = new List<string>(values);
// Call our methods.
var freqs = GetFrequencies(valuesList);
DisplaySortedFrequencies(freqs);
}
static Dictionary<string, int> GetFrequencies(List<string> values)
{
var result = new Dictionary<string, int>();
foreach (string value in values)
{
if (result.TryGetValue(value, out int count))
{
// Increase existing value.
result[value] = count + 1;
}
else
{
// New value, set to 1.
result.Add(value, 1);
}
}
// Return the dictionary.
return result;
}
static void DisplaySortedFrequencies(Dictionary<string, int> frequencies)
{
// Order pairs in dictionary from high to low frequency.
var sorted = from pair in frequencies
orderby pair.Value descending
select pair;
// Display all results in order.
foreach (var pair in sorted)
{
Console.WriteLine($
"{pair.Key} = {pair.Value}");
}
}
}
bird = 3
cat = 2
dog = 1
man = 1
frog = 1