2015/03/09

Dictionary to the rescue!

Programming language used: C#.net


Using Dictionary Generics can save your day. In fact, this is an ideal method of storing data which has a key for identifying the row information.

If you're thinking of when to use Dictionary, here are some scenarios that you should consider:
• Faster and easier way of looking up / searching values
• If you have rows that has unique values like ID you need to lookup, this is the best option

Dictionary can't help you that much if:
• You just need to loop the collection data you've generated
• You're not going to look or filter data for display

Dissecting the dictionary
Let us look into the dictionary and how it was designed:
Dictionary<TKey, TValue>
From the code snippet itself, we can define that:
TKey = This parameter defines unique value to retrieve TValue. This means that you can only put unique values as an argument without duplicate. If the compiler detects that you put a duplicate value, it will throw an exception and will not be happy to compile.
TValue = This parameter defines a set of values that you need to specify. Either you can specify a specific datatype or a class as an argument that returns a set of fields.


So, to get started, let me show you some sample code:          
Code snippet:
 

var dictionary = new Dictionary<String, Int32>();
            dictionary.Add("one",1);
            dictionary.Add("two", 2);
            dictionary.Add("three",3);

            foreach (var i in dictionary)
            {
                Console.WriteLine("{0}:\t{1}",i.Key,i.Value);
            }

Output:
one: 1
two: 2
three: 3

In the code snippet, we demonstrate adding keys and its respective value as collections to loop through the data using foreach. In addition, it's also worth mentioning that you can display both the TKey and TValue of the dictionary.

Tips & advice:
• This is not really an ideal way of using dictionary since you're not filtering anything. If this is the case, you may try to use List<T> for storing and retrieving list of values.
• Use Dictionary<TKey,TValue> only if you want a faster lookup or filtering something through a series of collections, though you could also use List<T> for filtering using lambda or LINQ if you're familiar of using it.

My next example uses filtering in addition of looping data:
Code snippet:
var dictionary = new Dictionary<String, Int32>();
            dictionary.Add("one",1);
            dictionary.Add("two", 2);
            dictionary.Add("three",3);

            foreach (var i in dictionary)
            {
                if (i.Key.Contains("one"))
                {
                    Console.WriteLine(i.Value);
                }
            }

Output:
1

This time, we used TKey parameter to filter the data that we're going to pull out using i.Key.Contains("one"). Though it's possible to filter something using other methods, using Dictionary will be the most recommended method.

Now, let us use some real-world example as our code snippet.
Code Snippet:
 static void DisplayIngredients()
         {
             Console.WriteLine("List of Ingredients");
             Console.WriteLine("Ingredient name\t\tDescription\tNumber of Stocks");
             foreach (var i in IngredientCollection())
             {
                 if (i.Key == "Carrots")
                 {
                     Console.WriteLine("{0}\t\t\t{1}\t{2}", i.Value.IngredientName, i.Value.Description, i.Value.NumberOfStocks);                    
                 }
                 else
                 {
                     Console.WriteLine("**not for display**");
                 }
             }
         }
 
 
 static Dictionary<String, Ingredients> IngredientCollection()
        {
            var lists = new Dictionary<String, Ingredients>();
            lists.Add("Carrots",new Ingredients("Carrots","Vegetables",5));
            lists.Add("Radish", new Ingredients("Radish", "Vegetables", 5));
            lists.Add("Orange", new Ingredients("Orange", "Fruits", 10));
            lists.Add("Apple", new Ingredients("Apple", "Fruits", 15));
            return lists;  
        }

class Ingredients
    {
        public Ingredients(String IngredientName, String Description, Int32 NumberOfStocks)
        {
            this.IngredientName = IngredientName;
            this.Description = Description;
            this.NumberOfStocks = NumberOfStocks;
        }
        public String IngredientName { get; set; }
        public String Description { get; set; }
        public Int32 NumberOfStocks { get; set; }
    }


Output:
Ingredient name Description Number of Stocks
Carrots                 Vegetables 5
**not for display**
**not for display**
**not for display**

Since we used i.Key to filter Carrots to be the only row to display, any other consequent rows were ignored and will not be displayed. And noticed that our TValue argument was not a datatype but rather a Class. You can also use Class as your argument for TValue.

CONCLUSION
I hope you learned something new based from my point of view. There are many methods to achieve and attain the storing of data and apply filtering. But today we've learned how to filter and display data using Dictionary.


Sources:
http://www.dotnetperls.com/dictionary
https://social.msdn.microsoft.com/Forums/en-US/79d75bfc-17a5-4007-8359-d2d828153430/which-is-best-to-use-list-or-dictionary-for-efficiency-of-code-execution?forum=csharplanguage
http://stackoverflow.com/questions/16802213/c-sharp-dictionary-vs-list-usage
http://www.c-sharpcorner.com/uploadfile/mahesh/dictionary-in-C-Sharp/