A lawyers Guide to Understanding Collections in C sharp: Part 1.

A lawyers Guide to Understanding Collections in C sharp: Part 1.

·

6 min read

Often times we find ourselves needing to store and organize data. Luckily for us, C sharp provides us with namespaces that can provide us with these awesome tools. We will be looking at three of the namespaces provided by c# :

1. System.Collections.Generic 

2. System.Collections.Concurrent 

3. System.Collections

1. System.Collections.Generic :

Whenever we intend to have data of the same type in our collection, then the .generic namespace is an ideal pick. The collections here a "strongly typed" meaning only similar data types can be added to the collection. for example:

List<string> sample = new List<string>();
sample.Add("tony");
System.Console.WriteLine(sample[0]);

//sample output
tony

The above list of type "string" can only take in strings. If we try to add ints or chars, we will get a build error. Do note that what goes in the <> is the type of data we want our list to contain. If for example, we wanted a list of students who belong to the student type, we can do that as follows:

public class Student
{
    public string Name { get; set; }
    public int ID { get; set; }
}

List<Student> Students = new List<Student> (){};

We will be looking at the following classes of the System.Collections.Generic namespace:

  • Dictionary: stores key-value pairs. Note that they are not ordered as you would have with lists. No index positions are given. Just as in your English dictionary, words are not numbered, rather they are accessed by their "keys" which is the word you are looking for.

  • List: items are ordered with each having an index position. I covered this collection type in this post:

  • Queue: this models the first in first out(FIFO). Like your typical queue on an ATM, who ever came first leaves first.

  • SortedList: this represents a collection of key/value pairs that are sorted by key based.

  • Stack: models the last in, first out (LIFO) collection of objects.

For this part we will be Introducing Dictionaries. Because of how vast dictionaries are, we will be having set of series with each going deeper. For now, as with all things, we will start from the beginning and get acclimated to dictionaries and how to use them in simple situations.

Dictionary:

In our day to day life we have cause to use a dictionary to look for the meaning of words(well before "googling" became the go to word search option).

The "key" was the word we wanted to know its meaning while its "value" was the definition of the said word. Picture that Oxford English dictionary as a data pool where information can be accessed by simply knowing the "key".

We create a dictionary in c# by providing the type of key and the value it can store. In the example below, we are stating that our dictionary key will be of type string and its value also of type string:

Dictionary<string, string>

we can proceed to declare and initialize a dictionary which we will call "emotion" as follows:

Dictionary<string, string> emotion = new Dictionary<string, string>() {
                {"tony", "happy"},
                {"sam", "sad"}
            };

To access each of the item in our dictionary, we can use the foreach loop. We provide the type (KeyValuePair) and the identifier(e.g kvp) in our loop:

 foreach ( KeyValuePair<string, string> kvp in emotion)
       {
         System.Console.WriteLine($"key: {kvp.Key}, value: {kvp.Value}");
        }

lets break the loop down and explain:

 foreach ( KeyValuePair<string, string> kvp in emotion)

The KeyValuePair<string, string> in our loop is just a way of saying each item is a key-value type which has a string as its key and a string also as its value.

Next the kvp is just an identifier with which we can access each of the item in our loop block such was when we do this (note i am using string interpolations below ):

System.Console.WriteLine($"key: {kvp.Key}, value: {kvp.Value}");

We use the kvp as our "identifier" of each item enabling us to perform dynamic and distinct operations on said item. In this case, we are simply printing out the item's key and value.

//sample output
key: tony, value: happy
key: sam, value: sad

Do note we could have implemented the foreach loop as follows:

foreach ( var kvp in emotion)
            {
                System.Console.WriteLine($"key: {kvp.Key}, value: {kvp.Value}");
            }

Either way works. I just explained the earlier in case you saw it in some code samples and became confused. How nice of me right? lol.

If we wanted to get just the value of "tony" we can do this:

System.Console.WriteLine(emotion["tony"]);
//output
happy

To add to the emotion dictionary we do this:

emotion.Add("paul", "blushing");
System.Console.WriteLine(emotion["paul"]);
//output
blushing

To remove from a dictionary we do this:

emotion.Remove("tony");

To check if a key exists in a dictionary we do this:

var result = emotion.ContainsKey("tony");
System.Console.WriteLine(result);
//output
True

What if we wanted our dictionary key's value to be a custom type we created? after all that is the beauty of c#. We will do that and even go deeper into dictionaries in the next part. Stay tuned.

sample code used for this demo:

using System;
using System.Text;
using System.Collections.Generic; 
using System.Linq;

namespace playground
{
    class Program
    {

        static void Main()
        {

            // var s1 = BuildDictionary();
            Dictionary<string, string> emotion = new Dictionary<string, string>() {
                {"tony", "happy"},
                {"sam", "sad"}
            };
            emotion.Add("paul", "blushing");
            emotion.Remove("tony");
            var result = emotion.ContainsKey("tony");
            System.Console.WriteLine(result);
            foreach ( var kvp in emotion)
            {
                System.Console.WriteLine($"key: {kvp.Key}, value: {kvp.Value}");
            }



        }

    }
}