Collection in c# with examples in detail

Updated : Nov 17, 2019 in Articles

Collection in c# with examples in detail

In this article we will learn about Collection in c# with examples in detail one by one let go

Introducing about Collections

Similar related data can be handled more simply and efficiently when grouped together into a collection. Instead of implementing separate(for grouped data ) code to handle each individual object, we can use the same code to process all the elements of a collection.

Collections in c# as part of the System.Collections and System.Collections.Generic namespace.

A collection in c# is a set of similar type objects that are grouped together. A collection is an object by itself manage by that objects example ArrayList, HashTable, Stack, Queue, LinkedList, SortedList etc.

Collection classes are derived from the interfaces class like ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator .

Benefits of collection in c#

Sorting capability,automatically indexed,best performance,memory management handled by automatically,synchronization provides thread safety,and easy way to implementing and access data

Collection types

  1. ArrayList
  2. HashTable
  3. Stack
  4. Queue
  5. SortedList
  6. BitArray

ArrayList in C#

Arrays are in c# similar data type it means it will store specify data type data only we know that but Arraylist in c# not similar datatype it will store any type of data like integer, string ,float..

ArrayList lst = new ArrayList();
    lst.Add(1);
    lst.Add("feret");
    lst.Add(34.5);
    lst.Add(null);
    lst.Add(true);

The capacity of an ArrayList is the number of elements the ArrayList can hold. The default initial capacity for an ArrayList is 0.

Elements in this collection can be accessed using an integer index and ArrayList accepts a null reference as a valid value and allows duplicate elements.

static void Main(string[] args)
        {
            ArrayList al = new ArrayList(100);
            al.Add("V1");
            al.Add("V2");
            Console.WriteLine(al.Add("S3"));
            al.Add("v5");
            al.Add("v6");
            al.AddRange(new string[] { "S1", "S2", "S3" });
            al.Insert(2, "D1");
            al.Remove("v4");
            al.RemoveAt(4);
            al.Sort();
            al.Reverse();
            al.TrimToSize();
            foreach (string s in al)
                Console.WriteLine(s);
            Console.WriteLine(al.Capacity + " " + al.Count);
       }

Hashtable in c#

Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be a null reference, but a value can be.

The capacity of a Hashtable is the number of elements the Hashtable can hold. The default initial capacity for a Hashtable is 0

HashTable Key must be unique but value need not be unique

static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht.Add(201, "vijay");
            ht.Add(202, "upraja");
            ht.Add(203, "evathi");
            ht.Add(204, "yed");
            ht.Add(205, "inayak");
            ht.Add(205, "amsi");
            ht.Add(205, "odhanda");
            ht.Remove(203);
            string value1 = ht[202].ToString();
            Console.WriteLine(value1);
            foreach (DictionaryEntry item in ht)
            {
                int key = (int)item.Key; string value = (string)item.Value;
            }
        }

SortedList in c#

SortedList is similar to the Hashtable class in that they implement the IDictionary interface, but they maintain their elements in sort order by key.

The properties that return keys and values are indexed, allowing efficient indexed retrieval.

static void Main(string[] args)
        {
            SortedList sl = new SortedList();
            sl.Add(201, "vijay");
            sl.Add(202, "upraja");
            sl.Add(203, "evathi");
            sl.Add(204, "yed");
            sl.Add(205, "inayak");
            sl.Add(205, "amsi");
            sl.Add(205, "odhanda");
            string value1 = sl[202].ToString();
            Console.WriteLine(value1);
            foreach (DictionaryEntry item in sl)
            {
                int key = (int)item.Key; string value = (string)item.Value; Console.WriteLine(key + " " + value);
            }
            string v = (string)sl.GetByIndex(2);
        }

Queue and Stack in c#

The Queue and Stack classes are useful when you need temporary storage for information, that is, when you might want to discard an element after retrieving its value.

Use Queue if you need to access the information in the same order that it is stored in the collection. Use Stack if you need to access the information in reverse order.

Stack

static void Main(string[] args)
  {
   Stack obj= new Stack();
   obj.Push(5);
   obj.Push(6);
   obj.Push(7);

   foreach (Object items in obj)
   {
    Console.WriteLine(items);
   }
    Console.WriteLine();
    Console.WriteLine("elements in the stack " +obj.Count);
    Console.WriteLine(" the elements position 3 "+obj.Contains(3));
    Console.ReadKey();
  }

Queue

static void Main(string[] args)
        {
            Queue items = new Queue();
            items.Enqueue("vv");
            items.Enqueue("cc");
            items.Enqueue("hh");

            foreach (Object obj in items)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine(); Console.WriteLine();
            Console.WriteLine("elements in the Queue " + items.Count);
            Console.WriteLine("Queue contain " + items.Contains(2));
            Console.ReadKey();
        }

BitArray in c#

The BitArray class is a collection class in which the capacity is always the same as the count. Elements are added to a BitArray by increasing the Length property; elements are deleted by decreasing the Length property.

Wap to display the Customer details using collections.

This is a console application to print the Customer details using collections.

Steps:

  1. Create a new console application project named CollectionDemoexample.
  2. Above the main class, write the below class.

using System;
using System.Collections.Generic;
namespace CollectionDemoexample
{
    public class Customer
    {
        public Customer(int id, string name)
        {
            CusId = id;
            CusName = name;
        }

        private int _CusId;
        private string _CusName;

        public int CusId
        {
            get
            {
                return _CusId;
            }
            set
            {
                _CusId = value;
            }
        }

        public string CusName
        {
            get
            {
                return _CusName;
            }
            set
            {
                _CusName = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myStr = new List<string>();
            myStr.Add("tutorials");
            myStr.Add("helper");
            myStr.Add("articels");

            for (int i = 0; i < myStr.Count; i++)
            {
                Console.Write(myStr[i]);
            }
            Console.WriteLine();

            //The Dictionary instance is represented by a collection of key and value pairs of any type.
            //Here we are passing int as key and Customer class as the value.
            Dictionary<int, Customer> cus = new Dictionary<int, Customer>();

            Customer obj1 = new Customer(1, "cus 1");
            Customer obj2 = new Customer(2, "cus 2");
            Customer obj3 = new Customer(3, "cus 3");

            cus.Add(obj1.CusId, obj1);
            cus.Add(obj2.CusId, obj2);
            cus.Add(obj3.CusId, obj3);

            //Iterating through the customers Dictionary with a foreach loop, the type returned is KeyValuePair<TKey, TValue>, where TKey is type int and 
            //TValue is type Customer because those are the types that the Customer Dictionary is defined with.

            foreach (KeyValuePair<int, Customer> cusKeyVal in cus)
            {
                //The parameters in the Console.WriteLine statement demonstrate this by printing outthe ID, obtained through the Key property, and the Name, 
                //obtained through the Name property of the Customer  instance that is returned by the Value property.
                Console.WriteLine(
                   "Customer ID: {0}, Name: {1}",
                   cusKeyVal.Key,
                   cusKeyVal.Value.CusName);
            }
            Console.ReadLine();
        }
    }
}


Collection in c# with examples in detail

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry
1

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x