A List
contains many elements in a C# program, but some may be duplicated. We can compute which ones are the most common, and which ones are the least common.
Using Dictionary
, we can loop through our string
List
and keep track of how many times each element occurs. This is fast—the Dictionary
has constant time lookup for each element.
In this program, 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.
GetFrequencies()
loops through the string
List
elements with foreach
. It uses TryGetValue
on a Dictionary
to maintain counts.Dictionary
has string
keys and int
values. So for each instance of "bird" we maintain a separate count int
.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
DisplaySortedFrequencies
Consider now the DisplaySortedFrequencies
method. We use a LINQ expression to sort the Dictionary
we created previously.
IOrderedEnumerable
.We find that our results indicate the string
"bird" occurs 3 times. This approach works not just for string
keys, but any sort of key (including ints).