articles

Home / DeveloperSection / Articles / Collection and Generic Collection Classes in C# .NET

Collection and Generic Collection Classes in C# .NET

Amit Singh27979 01-Jan-2011

Collection classes are used for data storage and manipulate (sort, insert, remove etc) the data.

Most of the collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes on the basis of more specialized data. These collection classes are defined in System.Collections.Generic.

Main collection classes which are used in c# as

  •    ArrayList Class
  •    HashTable Class
  •    Stack Class and Queue class etc.

The main properties of the collection classes are

·        Collection classes are defined as part of the System.Collection or System.Collections.Generic namespace.

·         Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.

·         Using generic collection classes provides increased type-safety and in some cases can provide better performance, especially when storing value types.

The following generic types correspond to existing collection types:

·         List is the generic class corresponding to ArrayList.

·        Dictionary is the generic class corresponding to Hashtable.

·         Collection is the generic class corresponding to collectionBase.Collection can be used as a base class, but unlike CollectionBase it is not abstract, making it much easier to use.

·         ReadOnlyCollection is the generic class corresponding to ReadonlyCollection. ReadOnlyCollection is not abstract, and has a constructor that makes it easy to expose an existing List as a read-only collection.

·         The Queue, stack and SortedList generic classes correspond to the respective nongeneric classes with the same names.

List Generic Class or ArrayList

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface using an array whose size is dynamically increased as required.

ArrayList is the part of datastructure.it show the simple list value. ArrayList class contain the Add, Insert Remove, RemoveAt and  Sort method and main properties like Capacity, Count etc. It is the part of System.Collection.

Syntax for creating a ArrayList:

ArrayList name = newArrayList();

Syntax for creating a List<T>:

List<Type> name=new List<Type>();

There are some basic properties and methods of List<T>

1.       Adding item to list

2.       Removing item to list

3.       Sort the list

4.       Insert the item into the list etc.

Add the item in ArrayList
Example:
  //make object of ArrayList class like countryList
        ArrayList countryList = newArrayList();
        //Add the country in the countrylist
        countryList.Add("India");
        countryList.Add("SriLanka");
        countryList.Add("SouthAfrica");
        countryList.Add("Australia");
        countryList.Add("England");
        //Show the countryList
        Response.Write("<b><u>Country List:</u></b><br/>");
        foreach (string country in countryList)
            Response.Write(country + "<br/>");
Add the item in List<T>
Example:
  //define the List here
        List<string> countryList = new List<string>();
        //use the add method to add the element in List
        countryList.Add("Rusea");
        countryList.Add("GreenLand");
        countryList.Add("India");
        countryList.Add("Pakistan");
        countryList.Add("US");
        //print the data on web page
        Response.Write("<b><u>Country List:</u></b><br/>");
        foreach (string country in countryList)
           Response.Write(country +"<br/>");

Output

Country List:
India
SriLanka
SouthAfrica
Australia
England

Remove the item from List<T>

List have following remove properties: Remove(), RemoveAt(), RemoveAll(), RemoveRange().

Example:

                     countryList.Remove("Pakistan");

Insert item into the List<T>

Insert method is used for Insert item into the List at any index of the list.

Example

countryList.Insert(2,"Pakistan");

Sort the item from the List<T>
Example:

countryList.Sort ();

 

Note: Other method which is used in List<T>

IndexOf(),Contains(),TrimExcess(),Clear() etc.

SortedList

The SortedList object contains items in key/value pairs. SortedList objects automatically sort the items in alphabetic or numeric order. Main method of sorted list are Add(), Remove(), IndexOfKey(), IndexOfValue(), GetKeyList(), GetKeyValue() etc. and to object key and values.

Example:
  //make object of Sorted List class like countryTable
        SortedList countrySList = newSortedList();
        //Add the country in the hashtable.Add(Object key,Object value)
        countrySList.Add(1, "india");
        countrySList.Add(2, "England");
        //Find the key and value by using DictionaryEntry
        foreach (DictionaryEntry country in countrySList)
            Response.Write(country.Key + " : " + country.Value + "<br/>");

Note:

Another Example related to SortedList check this link

http://www.mindstick.com/Articles/314386f2-11ec-4d39-a5b2-3d223dc4f51a/?Sorted%20list%20in%20CSharp.NET

How use the GetKeyList() and GetKeyValue() method
Example
IList countryKey = countrySList.GetKeyList();
foreach(Int32 country in countryKey)
    Response.Write(country +"<br/>");

Where IList is the interface of System.Collection.IList

IList countryValue = countrySList.GetValueList();
foreach (Int32 country in countryKey)
    Response.Write(country + "<br/>");

  HashTable

Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key. Both keys and values are Objects.

The main properties of HashTable are Key and Values and methods add (), remove (), contains () etc.

How use HashTable in .net
Example:
  //make object of HashTable class like countryTable
        Hashtable countryTable = newHashtable();
        //Add the country in the hashtable.Add(Object key,Object value)
        countryTable.Add(1, "India");
        countryTable.Add(2, "Srilanka");
        countryTable.Add(3, "England");
        //Find the key and value by using DictionaryEntry class
        foreach (DictionaryEntry country in countryTable)
            Response.Write(country.Key + " : " + country.Value +"<br/>");

Output:

Country List:
3 : England
2 : Srilanka
1 : India

Detailed concept on hash table sees this link:

http://www.mindstick.com/Articles/e54db9d2-181f-4beb-a986-6f969ff3bd8d/

 

Stack Class

It is worked as Last in first out (LIFO) when making the object of the stack class. Stack follow the two important method Push () and Pop ().  Push () method is used for inserting the item and pop () method is used for the removing the data.

Push () method

Example:

  //make object of Stack class 
        Stack countryStack = newStack();
        //Insert the item by push method
        countryStack.Push("India");
        countryStack.Push("England");
        //show the element in the stack
        foreach(string country in countryStack)
            Response.Write(country + "<br/>");

Output

England
India
<![if !supportLineBreakNewLine]>

Pop () method:

//Remove the item from the list

countryStack.Pop();

Queue Class

Queue work as first in first out (FIFO). Queue class has main method enqueue() and dequeue().Objects stored in a Queue are inserted at one end and removed from the other. The Queue provides additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue) or we can Peek (that is we will get the reference of first item) item from Queue. Queue accepts null reference as a valid value and allows duplicate elements.

The main method and properties of the queue class are Enqueue(), Dequeue() and Peek() etc.

Example:

  //make object of the queue class
        Queue countryQueue = newQueue();
        //insert the item in queue by Enqueue method
        countryQueue.Enqueue("India");
        countryQueue.Enqueue("England");
        //remove the item in queue by Dequeue method
        countryQueue.Dequeue();
        foreach (string country in countryQueue)
            Response.Write(country + "<br/>");
LinkedList<T>

Its main properties are Next and Previous so it is allow the forward and reverse traversal by these properties and its main methods AddAfter(), AddFirst(), AddBefore(), AddHead(), AddLast() and AddTail.



Updated 22-Apr-2020

Leave Comment

Comments

Liked By