Lesson 5
Advanced Dictionary Operations in C#
Advanced Dictionary Operations in C#

Greetings, fellow C# enthusiast! As we embark on our C# programming journey today, we will get up close and personal with a mighty helpful companion — Dictionary. Whether organizing a cookbook, tallying votes, or tracking inventory, Dictionary comes to the rescue, providing a way to handle pairs of data efficiently. Let's explore how Dictionary can transform complex tasks into straightforward ones through practical examples.

Problem 1: Word Counter

Consider this: you have an extensive text — perhaps a short story or a section of a report — and you want to analyze word usage. How many times does each word appear? This isn't just about curiosity; such a tool benefits writers aiming for diverse vocabulary.

Visualize yourself tasked with developing a feature for a text editor that gives feedback on word usage. A writer could use this feature to refine their work, ensuring they vary their vocabulary effectively.

Naive Approach

Consider iterating over the text word by word, keeping track of each instance in a list. This approach might work for a short sentence, but imagine scaling it up to an entire book! It becomes inefficient as you repeatedly wade through a growing list for each word you encounter. Each time a word is processed, you potentially iterate through the entire list of tracked words to update counts, resulting in a time complexity of O(n) for each word operation. As we evaluate each word in the text, this nested iteration produces an overall time complexity of O(n^2), which is inefficient for larger datasets.

C#
1using System; 2using System.Collections.Generic; 3 4class Solution { 5 public static void Main(string[] args) { 6 string text = "C# C# C#"; 7 List<string> wordsList = new List<string>(); 8 List<int> countList = new List<int>(); 9 string[] words = text.Split(' '); 10 11 foreach (string word in words) { 12 int index = wordsList.IndexOf(word); 13 if (index != -1) { 14 countList[index]++; 15 } else { 16 wordsList.Add(word); 17 countList.Add(1); 18 } 19 } 20 21 for (int i = 0; i < wordsList.Count; i++) { 22 Console.WriteLine($"{wordsList[i]}: {countList[i]}"); 23 } 24 } 25}

The Split method in C# divides a string into substrings based on specified delimiters (characters or strings) and returns an array of these substrings, with optional parameters for removing empty entries and limiting the number of substrings. For example, given the string "apple,banana,cherry" and using Split with the delimiter ',', the method call "apple,banana,cherry".Split(',') would return the array ["apple", "banana", "cherry"].

Efficient Approach

This is where Dictionary<string, int> shines like a knight in shining armor. With its efficient key manipulation functions, such as ContainsKey and TryGetValue, a Dictionary<string, int> allows for swift updates. Instead of a laborious search for each word, we can quickly check and update the count in constant time — a massive time-saver!

Let's break down the code step by step:

  1. We create a Dictionary<string, int> called wordCount to store words and their frequencies.
  2. Using the Split method, we divide the text into words.
  3. Then, for each word, we update the Dictionary using ContainsKey. If the word is already in the dictionary, we increment the count; otherwise, we create a new entry.

Here's how our C# approach does it:

C#
1using System; 2using System.Collections.Generic; 3 4class Solution { 5 public static void Main(string[] args) { 6 string text = "C# C# C#"; 7 Dictionary<string, int> wordCount = new Dictionary<string, int>(); 8 string[] words = text.Split(' '); 9 10 foreach (string word in words) { 11 if (wordCount.ContainsKey(word)) { 12 wordCount[word]++; 13 } else { 14 wordCount[word] = 1; 15 } 16 } 17 Console.WriteLine(string.Join(", ", wordCount)); 18 } 19}

Take the sentence "C# C# C#" for example. Our function would create a Dictionary with a single entry: {"C#", 3}. Simple and elegant!

Problem 2: Sum of Mapped Values

Suppose you're keeping track of inventory. You have items identified by their names and associated with their prices, all stored in a dictionary. How would you compute the total inventory value with minimal fuss?

Consider a situation in a retail store with a diverse product range, each with a unique identifier and price. To calculate the total inventory value, you need to efficiently access each item's price and tally them up.

Efficient Approach

Dictionary lays out items and prices on a neat table. It associates each product name (key) with its price (value). Using the Values property, you can directly access all the prices at once for summation, turning a complex task into a walk in the park.

Given a dictionary of items, we will use a loop to traverse the dictionary's values, adding them together into a sum.

Here's the C# magic:

C#
1using System; 2using System.Collections.Generic; 3 4class Solution { 5 public static void Main(string[] args) { 6 Dictionary<string, int> map = new Dictionary<string, int>(); 7 8 map["a"] = 10; 9 map["b"] = 6; 10 map["c"] = 12; 11 12 int sum = 0; 13 foreach (int value in map.Values) { 14 sum += value; 15 } 16 Console.WriteLine(sum); // 28 17 } 18}

Imagine a register tallying items — "apple: 1, banana: 2, cherry: 3" — our Dictionary would keep the count, and in the end, the sum would be a quick and accurate total: 6.

Lesson Summary

Today's foray into Dictionary has prepared you to conquer word counts, sum values, and manage unique elements with C#'s robust Dictionary. We witnessed firsthand the time-saving capabilities of dictionary operations, such as ContainsKey, updating keys, and accessing values.

You've absorbed the essence of practical examples, shedding light on how to operate dictionaries effectively. Embark on the practice exercises with zeal, and continue to nurture your passion for coding in C#.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.