Generics in .NET

Discussion in 'C#' started by MinalS, Mar 22, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    32
    Trophy Points:
    0
    .NET contains number of classes that help in generic collection creation. The generic classes are strongly typed. The methods perform sorting, reversing elements, element searching. User can create a Key/Value pair.

    Some of the generic collection classes in .NET are as shown below:
    1. List<T> class
    2. LinkedList<T> class
    3. Dictionary<TKey> class
    4. HashSet<T> class
    5. SortedDictionary<TKey,TValue> class

    1. List<T> class



    The List<T> class provides user with an easy substitute to an array. User can sort, reverse, and find the list of members in an array.

    Properties of List<T> class
    1. Capacity: It retrieves or sets the number of elements the object can hold
    2. Count: It is the number of items in the object
    3. Item: It is the set of element at the specific index.
    Methods of List<T> class
    1. AddRange(): It adds the items to the specific collection at the end of the object
    2. AsReadOnly(): It allows user to read the values of the objects
    3. Exists(): It checks whether the object matches the condition defined by the criteria.
    4. TrueForAll(): It checks whether element in the object matches the condition defined.
    The following code snippet demonstrates the use of the List<T> class.
    Code:
    public partial class Form1:Form
    {
        List<string> l1 = new List<string>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false;
            button3.Enabled=false;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            l1.Add("Score");
            l1.Add("Location");
            l1.Add("Captain");
            l1.Add("Country");
            ListLoad();
            button2.Enabled=true;
            button3.Enabled=true;
        }
        private void ListLoad()
        {
            listbox1.Items.Clear();
            for(int i=0;i<l1.Count;i++)
            {
                listBox1.Items.Add(l1[i]);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if( listBox1.SelectedIndex > -1)
            {
                l1.RemoveAt(listbox1.SelectedIndex);
                ListLoad();
            }
            else
            {
                MessageBox.Show("Select the value to be deleted");
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            l1.Reverse();
            ListLoad();
        }
    }
    

    2. LinkedList<T> class



    The LinkedList<T> class is a generic collection class that helps user to create collections acting as double linked lists. User can populate the list and access the values from them.

    Properties of LinkedList<T> class
    1. Count: It provides user with the number of items present in the object
    2. First: It retrieves the first node of the object
    3. Last: It retrieves the last node of the object
    Method of LinkedList<T> class
    1. AddBefore(): It adds the new node or value before the existing node
    2. AddAfter(): It adds a new node or value after the existing node
    3. Find(): It performs search to find the first node containing the specific value
    4. Remove(): It removes the first occurrence of the node or value from the object
    Consider the following example to demonstrate the LinkedList<T> class.
    Code:
    public partial class Form1:Form
    {
        LinkedList<string> l1 = new LinkedList<string>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false;
            button3.Enabled=false;
            button4.Enabled=false;
            button5.Enabled=false;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            l1.AddLast("Nick");
            l1.AddLast("Jerry");
            l1.AddLast("Sam");
            l1.AddLast("Harry");
            LoadLinkList();
            button2.Enabled=true;
            button3.Enabled=true;
            button4.Enabled=true;
            button5.Enabled=true;
        }
        private void LinkedList()
        {
            listBox1.Items.Clear();
            foreach(string obj in l1 )
            {
                listBox1.Items.Add(obj);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the value", " " , -1, -1);
            l1.AddFirst(temp);
            LinkedList();
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the value", " " , -1, -1);
            l1.AddLast(temp);
            LinkedList();
        }
    
        private void button4_Click(object sender, EventArgs e)
        {
            if(listBox1.Items.Count > 0)
            {
                l1.RemoveFirst();
                LinkedList();
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if ( listbox1.SelectedItem.Count > 0)
            {
                string temp = Microsoft.CSharp.Interaction.InputBox("Enter the value", " " , -1, -1);
                l1.AddAfter(l1.Find(listbox1.SelectedItem.ToString()), temp);
                LinkedList();
            }
            else
            {
                MessageBox.Show("Please add the item");
            }
        }
    }
    

    3. Dictionary<TKey, TValue> Class



    The Dictionary<TKey,TValue> class helps user to create generic collection for storing key and values. The keys are used for retrieving the values stored in them.

    Properties of the Dictionary<TKey,TValue> Class
    1. Count: It accesses the number of Key/Value pairs contained in the obejct
    2. Item: It retrieves or sets the value associated with the specific key
    3. Keys: It retrieves the collection containing keys from object
    4. Values: It retrieves the collection containing value from the object
    Methods of the Dictionary<TKey, TValue> Class
    1. Add(): It adds an item with the specified key and value into the object
    2. Clear(): It removes all the items from the object
    3. ContainsKey(): It checks whether the object contains the specific key
    4. TryGetValue(): It retrieves the value associated with the specific key from the object
    Consider an example to demonstrate the Dictionary class.
    Code:
    public partial class Form1:Form
    {
        Dictionary<int, string> dict = new Dictionary<int, string>();
        public Form1()
        {
            InitializeComponent();
        }
        public void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false
            button3.Enabled=false;
        }
        private void button1_Click( object sender, EventArgs e)
        {
            dict.Add(10, "Science");
            dict.Add(20, "Maths");
            dict.Add(30,"Hindi");
            dict.Add(40, "History");
            dict.Add(50,"English");
            LoadDict();
            button2.Enabled=true;
            button3.Eanbled=true;
        }
        private void LoadDict()
        {
            listview1.Items.Clear();
            foreach(object obj in dict.Keys)
            {
                ListViewItem l1 = listview1.Items.Add(obj.ToString());
                l1.SubItems.Add(dict[(int) obj );
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the Key", " " " " , -1, -1);
            if(dict.ContainsKey(Convert.ToInt32(temp)))
            {
                MessageBox.Show("Dictionary contains key");
            }
            else
            {
                MessageBox.Show("Dictionary does not contain key");
            }
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the Value", " " " " , -1, -1);
            if(dict.ContainsValue(temp))
            {
                MessageBox.Show("Dictionary contains value");
            }
            else
            {
                MessageBox.Show("Dictionary does not contain value");
            }
        }
    }
    

    4. HashSet<T> Class



    The HashSet<T> class represents set of values. It does not contain any duplicate elements. The elements are not stored in a particular order.

    Methods of HashSet<T> Class
    1. IntersectWith(): It modifies the object to contain elements the present in itself.
    2. IsProperSubsetOf(): It checks whether or not the object is in proper subset of the collection
    3. IsSupersetOf(): It checks whether or not the object is a superset of the specified condition
    4. RemoveWhere(): It removes all the elements that match the condition defined in the criteria.
    5. UnionWith(): It changes the current object to contain all elements present in object itself and collection
    Consider an example to demonstrate the HashSet<T> class.
    Code:
    public partial class Form1:Form
    {
        HashSet<int> s1 = new HashSet<int>();
        HashSet<int>s2 = new HashSet<int>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false;
            button3.Enabled=false;
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            for ( int i=0; i<10; i++)
            {    
                s1.Add(i);
            }
            for ( int i=5;i<20;i++)
            {
                s2.Add(i);
            }
            LoadHash();
            button2.Eanbled=true;
            button3.Eanbled=true;
        }
        private void LoadSet()
        {
            listBox1.Items.Clear();
            int[ ] obj1 = s1.ToArray();
            for ( int i=0;i<s1.Count;i++)
            {
                listBox1.Items.Add(obj1[i].ToString());
            }
            listBox2.Items.Clear();
            int[ ] obj2 = s2.ToArray();
            for ( int i=0;i<s2.Count;i++)
            {
                listBox2.Items.Add(obj2[i].ToString());
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            listbox3.Items.Clear();
            HashSet<int> union = new HashSet<int>(s1);
            union.UnionWith(s2);
            foreach(int i in union)
            {
                listbox3.Items.Add(i.ToString());
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            listbox3.Items.Clear();
            HashSet<int> intersect = new HashSet<int>(s1);
            union.IntersectWith(s2);
            foreach(int i in intersect)
            {
                listbox3.Items.Add(i.ToString());
            }
        }
    

    5. SortedDicitonary<TKey,TValue> Class



    The SortedDictionary<TKey,TValue> class adds and sorts the items on the key basis.

    Properties of SortedDictionary<TKey,TValue> class
    1. Item: It sets or retrieves the value with the specific key
    2. Keys: It retrieves the collection containing keys from the object
    3. Values: It retrieves the collection containing values from the object
    4. Count: It retrieves the number of Key/Value pairs in the object
    Methods of SortedDictionary<TKey,TValue> class
    1. Add(): It adds an item with the specified key and value into the object
    2. TryGetValue(): It gets the value of the associated key
    3. ContainsKey(): It checks whether the object contains item with the specific value
    Code:
    public partial class Form1:Form
    {
        SortedDictionary<int, string> dict1 = new SortedDictionary<int, string>();
        public Form1()
        {
            InitializeComponent();
        }
        public void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false;
            button3.Enabled=false;
        }
        private void button1_Click( object sender, EventArgs e)
        {
            dict1.Add(10, "Science");
            dict1.Add(20, "Maths");
            dict1.Add(30,"Hindi");
            dict1.Add(40, "History");
            dict1.Add(50,"English");
            LoadSrtDict();
            button2.Enabled=true;
            button3.Enabled=true;
        }
        private void LoadSrtDict()
        {
            listview1.Items.Clear();
            foreach(object obj in dict1.Keys)
            {
                ListViewItem l1 = listview1.Items.Add(obj.ToString());
                l1.SubItems.Add(dict1[(int) obj );
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the Key", " " " " , -1, -1);
            if(dict1.ContainsKey(Convert.ToInt32(temp)))
            {
                MessageBox.Show(" Sorted Dictionary contains key");
            }
            else
            {
                MessageBox.Show(" Sorted Dictionary does not contain key");
            }
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            string temp = Microsoft.CSharp.Interaction.InputBox("Enter the Value", " " " " , -1, -1);
            if(dict1.ContainsValue(temp))
            {
                MessageBox.Show("Sorted Dictionary contains value");
            }
            else
            {
                MessageBox.Show(" Sorted Dictionary does not contain value");
            }
        }
    }
    
     
    Sagar Jaybhay likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice