Collection and Generics-Part 2(List and Dictionaries)

One can manage a group of items/objects using arrays or collections, we have already talked about arrays in the previous lecture, today we will talk about collections

Collections provide a more flexible way to work with a group of objects.

Yes flexible, collections can grow and shrink dynamically. One of the greatest advantage over Arrays.

There are many collections provided by .Net framework, we will look at the most used collection classes

Generic List
Strongly typed list of elements that can be accessed by using positional index number.

Declaration
List<string> EmpNameList;

Declared EmpNameList which will hold elements of type string

Initialization
EmpNameList = new List<string>();

Operations
            //Add Element
            EmpNameList.Add("Employee1");
 
            //Remove Element
            EmpNameList.Remove("Employee1");
 
            //Add at specified index
            EmpNameList.Insert(2, "Employee2");

Declare Initialize Add All In One
var EmpNameList = new List<string>() { "Employee1", "Employee2" };

Iteration
You can iterate List using for and for each loop

for (int i = 0; i < EmpNameList.Count; i++)
     Console.WriteLine(EmpNameList[i]);
 
foreach (var item in EmpNameList)
      Console.WriteLine(item);

Important Points
  1. A generic list can grow dynamically as oppose to an Array
  2. Strongly typed
So the point is when you are not aware of the size of the group you are going to manage, it's better to go with a generic list

Generic Dictionaries
Strongly typed collection of key and values.
Dictionaries are used mainly when you need to manage a collection of items by key.

Suppose you are testing an application, which has a state code drop-down and state name textarea/label.Dropdown contains values like "CA", "NY" etc

If the user selects "CA" value in the drop-down then label text changes to the name of the state having the code "CA" ie California

We already know that state codes are unique and represent a single state.

So to automate this scenario we need test data with state codes and their respective state names.
We can solve this using Arrays or list, where we will have 2 lists, one for state codes and other with their state names and we will make sure state names are inserted according to state code index in other lists.
We will iterate over state code list and select the code and verify if the label text matches with the state name of the 2nd list.

We can refactor this and have a better solution using a generic dictionary
We already know that state codes are unique and represent a single state, we can store them in dictionary collection and in our test case we will iterate over dictionary collection and verify the label text matches with the value of dictionary key, check below code


//Initialization
Dictionary<string, string> stateCollection = new Dictionary<string, string>();

We will add state code and their respective state name in the dictionary collection

//Adding Data
stateCollection.Add("CA", "California");
stateCollection.Add("CO", "Colorado");
stateCollection.Add("NY", "New York");
stateCollection.Add("TX", "Texas");

Now we will iterate the dictionary collection keys and for each key, we will get its value and compare with the label text value

foreach(var stateCode in stateCollection.Keys)
{
//Select the state code in drop down
Console.WriteLine($"Selected state code in drop down {stateCode}");
 
//Get the state name from test data
Console.WriteLine($"State name for state code {stateCode} is {stateCollection[stateCode]}");
 
//Verify if the state name matches
Console.WriteLine("Verified");
 
Console.Read();
               
           }


Below output snap

Selected state code in drop down is CA
State name for state code CA is California
Verified
Selected state code in drop down is CO
State name for state code CO is Colorado
Verified
Selected state code in drop down is NY
State name for state code NY is New York
Verified
Selected state code in drop down is TX
State name for state code TX is Texas
Verified

Solution using dictionaries looks cleaner, now we look at some important points

Important points
  1. Use the Dictionary to manage collection by key
  2. If there is no key then avoid using a dictionary
  3. Key must be unique
  4. Key must not change
  5. Key cannot be null
Now we will look at some best practices while retrieving a value from dictionaries

Retrieving Value
As we covered earlier we can retrieve the value from the dictionary using its key


var value = stateCollection["CA"];

Now suppose the key is not present in the dictionary, then what will above code return?

Think .....

Yes. An Exception, to be specific an KeyNotFoundException.

How can we avoid this?
Can we check if the key exists and then accordingly ask for its value?
Yes. we can use the ContainsKey method to check the key exists.

Check the refactored solution below

if (stateCollection.ContainsKey("CA1"))
           {
               //Key found
               //Continue with your code
           }
           else
           {
               Console.WriteLine("Key not found ");
               //Return to the caller 
               //Fail the test case
 
           }

Alternatively, you can use TryGetValue method as well, check below code

string value = string.Empty;
           stateCollection.TryGetValue("CA1", out value);
 
           if(!string.IsNullOrEmpty(value))
           {
               //Key found
               //Continue with your code
           }
           else
           {
               Console.WriteLine("Key not found ");
               //Return to the caller 
               //Fail the test case
 
           }

Well that's what I had for this lecture, stay tuned for the next lecture 👦

Comments

Popular posts from this blog

Specflow -Part3(Working with tables using Specflow.Assist.Dynamic)

Specflow -Part4(Specflow Scenario Outline and Feature Background )

Specflow -Part6(Specflow Hooks)