Saturday, March 19, 2016

C# - Working with collections

Overview

The namespace “System. Collections” contain different types of collections that you can use to implement a more logical code structure. 

This article will help you to understand the available options and how can you use them during your development process.

The ‘Array List’ class

The ArrayList class, allows us to create ‘Dynamic’ array that can store different types and objects in a single collection (Yes! You can store strings, int and any other type on single collection).

For example:

class Program
    {
        static void Main(string[] args)
        {
            string a = "Hallo!!";
            int b = 4 ;
            ArrayList FirstExample = new ArrayList() {a,b};
        }
    }

Like a basic array, collections have some methods and properties that we can use  to control the collection values and size, Examples: 

The ‘ADD’ method
After declaring an array, you can initialize it in the declaration phase or afterwords. If you decide to use the second option you need to use the ‘Add’ method.

Example:

class Program
    {
        static void Main(string[] args)
        {
            char a = 'A';
            char b = 'B';
            ArrayList AddValue = new ArrayList();

            AddValue.Add(a);
            AddValue.Add(b);
        }
    }

The ‘Remove’ method
This method will help use to remove an object based on object name (you must specify the exact name because it’s case sensitive…).

class Program
    {
        static void Main(string[] args)
        {          
            ArrayList RemoveValues = new ArrayList() { 'A', 'B', 'C', 'D', 'E' };
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values Before removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
            RemoveValues.Remove('C');
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values After removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
        }

        private static void PrintCollection(ArrayList ArrayNName)
        {
            int counter = 0;
            foreach (var item in ArrayNName)
            {
                Console.WriteLine("Index  : {0} , Value : {1} ",counter,item);
                counter++;
            }
        }
    }

Result:
Collection values Before removal:
Index: 0, Value: A
Index: 1, Value: B
Index: 2, Value: C
Index: 3, Value: D
Index: 4, Value: E

Collection values After removal:
Index: 0, Value: A
Index: 1, Value: B
Index: 2, Value: D
Index: 3, Value: E

The ‘RemoveAt’ method
This method remove an object based on object location

class Program
    {
        static void Main(string[] args)
        {          
            ArrayList RemoveValues = new ArrayList() { 'A', 'B', 'C', 'D', 'E' };
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values Before removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
            RemoveValues.RemoveAt(2); //removing the object under indexer 2
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values After removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
        }

        private static void PrintCollection(ArrayList ArrayNName)
        {
            int counter = 0;
            foreach (var item in ArrayNName)
            {
                Console.WriteLine("Index  : {0} , Value : {1} ",counter,item);
                counter++;
            }
        }
    }

Result:
Collection values Before removal:
Index: 0, Value: A
Index: 1, Value: B
Index: 2, Value: C
Index: 3, Value: D
Index: 4, Value: E

Collection values After removal:
Index: 0, Value: A
Index: 1, Value: B
Index: 2, Value: D
Index: 3, Value: E

The ‘RemoveRange’ method
This method remove a range of objects based on Start and indexes counter for removal.

class Program
    {
        static void Main(string[] args)
        {          
            ArrayList RemoveValues = new ArrayList() { 'A', 'B', 'C', 'D', 'E' };
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values Before removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
            RemoveValues.RemoveRange(1,2); //removing 2 objects after indexer 1
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Collection values After removal :");
            Console.ResetColor();
            PrintCollection(RemoveValues);
        }

        private static void PrintCollection(ArrayList ArrayNName)
        {
            int counter = 0;
            foreach (var item in ArrayNName)
            {
                Console.WriteLine("Index  : {0} , Value : {1} ",counter,item);
                counter++;
            }
        }
    }

Result:
Collection values Before removal:
Index: 0, Value: A
Index: 1, Value: B
Index: 2, Value: C
Index: 3, Value: D
Index: 4, Value: E

Collection values After removal:
Index: 0, Value: A
Index: 1, Value: D
Index: 2, Value: E

The ‘’Count’ and ‘Capacity’ methods
The ‘Count’ method return the actual numbers of initialized indexes resides in collection, from the other end the ‘Capacity’ method returns the collection size (initialized and not initialized indexes).

static void Main(string[] args)
        {          
            ArrayList SizeMethods = new ArrayList() { 'A', 'B', 'C', 'D', 'E' };
            Console.WriteLine("Collection Size : " + SizeMethods.Capacity);
            Console.WriteLine("Initialized indexes:  " + SizeMethods.Count);
        }

Result:
Collection Size: 8
Initialized indexes:  5

The ‘’Clear method
This method clear all objects in collection

static void Main(string[] args)
        {          
            ArrayList ClearMethod = new ArrayList() { 'A', 'B', 'C', 'D', 'E' };
            Console.WriteLine("Objects in collection :" + ClearMethod.Count);
            ClearMethod.Clear(); //Remove all objects
            Console.WriteLine();
            Console.WriteLine("Objects in collection :" + ClearMethod.Count);
        }
Result:
Objects in collection: 5
Objects in collection: 0

The ‘Contains’ method
This method search in collection for specific object name and return Boolean value (True or False).
static void Main(string[] args)
        {          
            ArrayList ContainsMethod = new ArrayList() { 'A', 'B', 'C'};    
            Console.WriteLine("Collection contain object A ?\nResult:" + ContainsMethod.Contains('A'));
            Console.WriteLine("Collection contain object D ?\nResult:" + ContainsMethod.Contains('D'));        }

Result:
Collection contain object A?
Result: True
Collection contain object D?
Result: False

The ‘IndexOf’ method
This method receive object name and search it in collection, if object founds it return integer with the object indexer value if value not found it’s return ‘-1’ as false.

static void Main(string[] args)
        {          
            ArrayList ContainsMethod = new ArrayList() { 'A', 'B', 'C'};
            Console.WriteLine("Index Value: " + ContainsMethod.IndexOf('C'));
            Console.WriteLine("Index Value: " + ContainsMethod.IndexOf('4'));          
        }

Result:
Index Value: 2
Index Value: -1

Dictionary class

The dictionary class should receive two parameters before it can be used (Key Type, Type Value).


Note!
You must add reference to “System.Collections.Generic”, before you can use this class

 Example:
The following code will demonstrate the basics of the dictionary collection

Static void Main (string [] args)
        {               
            Dictionary<intstring> Names = new Dictionary<intstring>();           
        }

Dictionaries methods:

Adding data
This method will be used to add values to dictionary by receiving two parameters:

static void Main(string[] args)
        {               
            Dictionary<intstring> Names = new Dictionary<intstring>();
            Names.Add(1, "Dany");
            Names.Add(1, "Alex");
        }

Reading dictionary data
This section will offer a few ways to read values from a dictionary,

Code:
  class Program
    {
        static void Main(string[] args)
        {               
            Dictionary<intstring> Names = new Dictionary<intstring>();
            Names.Add(1, "Dany");
            Names.Add(2, "Alex");
            Names.Add(3, "Oleg");
            Names.Add(4, "Casper");

            //Option 1: Print all values in a collection
            PrintingAllkeys(Names);      

            //Option 2:Print All keys in a collection
            PrintingAllValues(Names);

            //Option 3:Print All Values in a collection
            PrintingDictionaryValues(Names);
        }

        private static void PrintingAllkeys(Dictionary<intstring> Names)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Option 1 : \n");
            Console.ResetColor();
            foreach (KeyValuePair<intstring> item in Names)
            {
                Console.WriteLine("Key = {0}", item.Key);
            }
        }
        private static void PrintingAllValues(Dictionary<intstring> Names)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\nOption 2 : \n");
            Console.ResetColor();
            foreach (KeyValuePair<intstring> item in Names)
            {
                Console.WriteLine("Value = {0}", item.Value);
            }
        }
        private static void PrintingDictionaryValues(Dictionary<intstring> Names)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\nOption 3 : \n");
            Console.ResetColor();
            foreach (KeyValuePair<intstring> item in Names)
            {
                Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);
            }
        }    
    }

Result:

Option 1:
Key = 1
Key = 2
Key = 3
Key = 4

Option 2:

Value = Dany
Value = Alex
Value = Oleg
Value = Casper

Option 3:
Key = 1 | Value = Dany
Key = 2 | Value = Alex
Key = 3 | Value = Oleg
Key = 4 | Value = Casper

Removing dictionary data
This section demonstrate how to remove values from dictionaries using 2 different methods.

Code:
class Program
    {
        static void Main(string[] args)
        {               
            Dictionary<intstring> Names = new Dictionary<intstring>();
            Names.Add(1, "Dany");
            Names.Add(2, "Alex");
            Names.Add(3, "Oleg");
            Names.Add(4, "Casper");                     
            RemoveItemByKey(Names);           
        }

         private static void RemoveItemByKey(Dictionary<intstring> Names)
        {
            int TMP = 0;
            int KeyForRemoval;
            try
            {
                do
                {
                    Console.WriteLine("********App for items removal********:  ");
                    Console.WriteLine("[1] = Display Dictionary values");
                    Console.WriteLine("[2] = Remove Specific Item");
                    Console.WriteLine("[3] = Remove All Items");
                    Console.WriteLine("[4] = Exit");
                    TMP = int.Parse(Console.ReadLine());
                    switch (TMP)
                    {
                        case 1:
                            PrintingDictionaryValues(Names);
                            break;

                        case 2:
                            Console.WriteLine("Select Key for removal");
                            Names.Remove(KeyForRemoval = int.Parse(Console.ReadLine()));
                            break;

                        case 3:
                            Names.Clear();
                            break;

                        case 4:
                            TMP = 4;

                            break;
                    }
                while (TMP != 4);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }     

        private static void PrintingDictionaryValues(Dictionary<intstring> Names)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Dictionary Values: \n");
            Console.ResetColor();
            foreach (KeyValuePair<intstring> item in Names)
            {
                Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);
            }
            Console.WriteLine();
        }      
    }

Result:

********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items
[4] = Exit
1
Dictionary Values:
Key = 1 | Value = Dany
Key = 2 | Value = Alex
Key = 3 | Value = Oleg
Key = 4 | Value = Casper

 ********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items 
[4] = Exit
2
Select Key for removal
4

********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items
[4] = Exit
1

Dictionary Values:
Key = 1 | Value = Dany
Key = 2 | Value = Alex
Key = 3 | Value = Oleg

********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items
[4] = Exit

3
********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items
[4] = Exit

1
Dictionary Values:

********App for items removal********:
[1] = Display Dictionary values
[2] = Remove Specific Item
[3] = Remove All Items
[4] = Exit

4
Changing a specific value in a Dictionary
This example will demonstrate how to modify value based on a given key.

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

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> NumberOfCitizens = new Dictionary<string, int>();
            NumberOfCitizens.Add("London" ,1000);
            NumberOfCitizens.Add("Paris",20000);
            NumberOfCitizens.Add("NewYork",300000);
            NumberOfCitizens.Add("Tokyo", 4000000);
            Console.WriteLine("Dictionary values Before:");
            PrintingDictionaryValues(NumberOfCitizens);

            //Changing a specific value
            ChangingValue(NumberOfCitizens, "Paris", 0);

            Console.WriteLine("Dictionary values After:");

            PrintingDictionaryValues(NumberOfCitizens); 
        }

        private static void ChangingValue(Dictionary<string, int> Citizens, string value, int newvalue)
        {
            Citizens[value] = newvalue;
        }      
        private static void PrintingDictionaryValues(Dictionary<string,int> Names)
        {
            foreach (KeyValuePair<string,int > item in Names)
            {
                if (item.Key== "Paris")
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);
                    Console.ResetColor();
                }
                else
                {
                    Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);               
                }                 
            }
            Console.WriteLine();
        }      
    }
}

Result:
Dictionary values Before:

Key = London | Value = 1000
Key = Paris | Value = 20000
Key = NewYork | Value = 300000
Key = Tokyo | Value = 4000000

Dictionary values After:
Key = London | Value = 1000
Key = Paris | Value = 0
Key = NewYork | Value = 300000
Key = Tokyo | Value = 4000000

Contains Key Method
This code will demonstrate how to validate if dictionary contain specific key and return False or True

Code:
class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> NumberOfCitizens = new Dictionary<string, int>();
            NumberOfCitizens.Add("London" ,1000);
            NumberOfCitizens.Add("Paris",20000);
            NumberOfCitizens.Add("NewYork",300000);
            NumberOfCitizens.Add("Tokyo", 4000000);

            Console.WriteLine("Keys Validation:");
            ValidateForKey(NumberOfCitizens,"London");
            ValidateForKey(NumberOfCitizens, "BlaBla");           
        }

        private static void ValidateForKey(Dictionary<string, int> Validation , string key)
        {
            if (Validation.ContainsKey(key))
            {
                Console.WriteLine("Key Available:{0}\nKey Value:{1}", "Yes", Validation[key]); 
            }
            else
            {
                Console.WriteLine("Key Available:No");                 
            }
        }

        private static void PrintingDictionaryValues(Dictionary<string,int> Names)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Dictionary Values: \n");
            Console.ResetColor();
            foreach (KeyValuePair<string,int > item in Names)
            {
                if (item.Key== "Paris")
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);
                    Console.ResetColor();
                }
                else
                {
                    Console.WriteLine("Key = {0} | Value = {1}", item.Key, item.Value);               
                }                 
            }
            Console.WriteLine();
        }      
    }

Result:
Keys Validation:
Key Available:Yes
Key Value:1000
Key Available: No

Contains Method
This method will check the existence of a specific value.

Code:
    static void Main(string[] args)
        {
            Dictionary<string, int> NumberOfCitizens = new Dictionary<string, int>();
            NumberOfCitizens.Add("London" ,1000);
            NumberOfCitizens.Add("Paris",20000);
            NumberOfCitizens.Add("NewYork",300000);
            NumberOfCitizens.Add("Tokyo", 4000000);

            Console.WriteLine("Values Validation:");
            ValidateForValue(NumberOfCitizens, 300000);
            ValidateForValue(NumberOfCitizens, 0);          
        }

         private static void ValidateForValue(Dictionary<string, int> NumberOfCitizens, int value)
        {
            if (NumberOfCitizens.ContainsValue(value))
            {
                Console.WriteLine("Value Available");               
            }
            else
            {
                Console.WriteLine("Value is Not Available");
            }
        }  

Result:
Values Validation:
Value Available
Value is Not Available

No comments:

Post a Comment

My Presentations