Home
C#
List Common Elements
Updated Sep 14, 2023
Dot Net Perls
Common elements. 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.
Info GetFrequencies() loops through the string List elements with foreach. It uses TryGetValue on a Dictionary to maintain counts.
foreach
Dictionary TryGetValue
out
Tip The 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
Notes, DisplaySortedFrequencies. Consider now the DisplaySortedFrequencies method. We use a LINQ expression to sort the Dictionary we created previously.
And We sort in descending order, so the most frequent strings (like "bird") are placed first in the resulting IOrderedEnumerable.
Results, summary. 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).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 14, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen