Collections in C# : Most used concept .

Your Ad Here

Collection Classes In C#

All the collection classes are contained in the

System.Collections namespace

The System.Collections namespace provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it.
The interfaces that are defined in this namespace include:
  1. · IEnumerable
  2. · IEnumerator
  3. · ICollection
  4. · IList
  5. · IDictionary
The following are the classes that are derived from the ICollection interface.
  1. · System.Collections.Stack
  2. · System.Collections.Queue
  3. · System.Collections.BitArray
  4. · System.Collections.Specialized.NameValueCollection
The IDictionary interface represents collections that have name value pairs. The ollections that inherit the IDictionary interface include:
  1. · System.Collections.SortedList
  2. · System.Collections.Hashtable
  3. · System.Collections.Specialized.HybridDictionary
  4. · System.Collections.Specialized.ListDictionary
The IList interface represents collections that only have value. The following are the classes that extend this interface.
  1. · System.Array
  2. · System.Collections.ArrayList
  3. · System.Collections.Specialized.StringCollection
The IEnumerable Interface
An enumerator is an object that provides a forward, read-only cursor for a set of items. The IEnumerable interface has one method called the GetEnumerator() method. This method returns an object that implements the IEnumerator interface. The code snippet below illustrates how an enumerator can be used to iterate though a list or collection of items.

The IEnumerable Interface

An enumerator is an object that provides a forward, read-only cursor for a set of items. The IEnumerable interface has one method called the GetEnumerator() method. This method returnsan object that implements the IEnumerator interface. The code snippet below illustrates how an enumerator can be used to iterate though a list or collection of items.

Sample Code

String names[]=new String[2] {”Jemmy”,”Jini”};
for(IEnumerator e =names.GetEnumerator();
e.MoveNext();
Response.Write(e.Current));

Note that the GetEnumerator() method returns an enumerator object each time it is called. Further, the loop contains the Response.Write statement in its re-initializer portion, which is perfectly valid. The condition being evaluated is whether the MoveNext() method returns a value of true. The MoveNext() method returns true as long as there are items in the collection. The Current property returns the current object and is automatically typecast to string by making a call to the ToString() method implicitly.The foreach method can also be used in this case, as it calls the enumerator implicitly. The above code can be re-written using a foreach loop as follows:

Sample Code

String names[]=new String[2] {”jemmy”,”Jini”};
foreach(string str in names)
Response.Write(str);

ArrayList

The ArrayList class is a dynamic array of heterogeneous objects. Note that in an array we can store only objects of the same type. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only. We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object type. An ArrayList uses its indexes to refer to a particular object stored in its collection. The Count property gives the total number of items stored in the ArrayList object. The Capacity property gets or sets the number of items that the ArrayList object can contain. Objects are added using the Add() method of the ArrayList and removed using its Remove() method. An example of usage of an ArrayList is given below.

Sample Code

using System;
using System.Collections;

class Test
{
static void Main()
{
int i = 100;
double d = 20.5;
ArrayList arrayList = new ArrayList();
arrayList.Add("Jemmy");
arrayList.Add(i);
arrayList.Add(d);
for (int index = 0; index 0)
Console.WriteLine(stackObject.Pop());
Console.ReadLine();
}
}

The Push() method is responsible for storing items in the Stack and the method Pop() removes them one at a time from the top of the Stack.

Queue

Unlike the Stack class, the Queue is a data structure that provides a First-in-First-out collection of items of the System.Object type. The newly added items are stored at the end or the rear of the Queue and items are deleted from the front of the Queue. The following code shows how the Queue class can be used.

Sample Code

using System;
using System.Collections;

class Test
{
static void Main()
{
Queue queueObject = new Queue();
queueObject.Enqueue("John Smith");
queueObject.Enqueue("Brown Smith");
queueObject.Enqueue("Jini");
while (queueObject.Count > 0)
Console.WriteLine(queueObject.Dequeue());
Console.ReadLine();
}
}

The Enqueue() method is responsible for storing items at the rear of the Queue and the method Dequeue() removes them one at a time from the front of the Queue.

BitArray

The BitArray class can be used to store bits in an array. They can be set to true or false, depending on the parameter supplied at the time of creating the BitArray object. The following is an example of its usage.

BitArray bitArray = new BitArray(5,false);
Or
BitArray bitArray = new BitArray(5,true);

Similar to the other collections discussed above, the BitArray class also contains the Count property to get the number of items stored in this collection of bit values. The following methods of the BitArray class allow logical bit operation.

  1. · And
  2. · Or
  3. · Not
  4. · Xor
Hashtable
The Hashtable provides a faster way of storage and retrieval of items of the object type. The Hashtable class provides support for key based searching. These keys are unique hash codes that are unique to a specific type. The GetHashCode() method of the Hashtable class returns the hash code for an object instance. The following code snippet shows how we can use a Hashtable class.

Sample Code

using System;
using System.Collections;

class Test
{
static void Main()
{
Hashtable hashTable = new Hashtable();
hashTable.Add(1, "John Brown ");
hashTable.Add(3, "Alex Smith");
Console.WriteLine("The keysare:--");
foreach (int k in hashTable.Keys)
{
Console.WriteLine(k);
}
Console.WriteLine("Please enter the keyto search");
int p = int.Parse(Console.ReadLine());
Console.WriteLine(hashTable[3].ToString());
}
}

To remove an item from the Hashtable class, the Remove() method is used. The statement hashTable.Remove(3) would remove the item “Jini” from the Hashtable object created in the above code. The code shown above can also be written as shown below to display the contents of the Hashtable object using IDictionaryEnumerator.

Sample Code

using System;
using System.Collections;

class Test
{
static void Main()
{
Hashtable hashTable = new Hashtable();
hashTable.Add(1, "Joydip");
hashTable.Add(2, "Manashi");
hashTable.Add(3, "Jini");
hashTable.Add(4, "Piku");
Console.WriteLine("The keysare:--");
IDictionaryEnumerator en =hashTable.GetEnumerator();
string str = String.Empty;

while (en.MoveNext())
{
str = en.Value.ToString();
Console.WriteLine(str);
}
}
}

SortedList

The SortedList class allows items of the System.Object type to be placed in the collection using key value pairs and, at the same time, supports sorting.
The following code shows how we can use a SortedList.

Sample Code

using System;
using System.Collections;
using System.Collections.Specialized;

class Test
{
static void Main()
{
SortedList sortedList = new SortedList();
sortedList.Add(1, "John Brown ");
sortedList.Add(3, "Alex Smith");

Console.WriteLine("Displaying thenames");

foreach (string str in sortedList.Values)
{
Console.WriteLine(str);
}
}
}

The same code can be written using IDictionaryEnumerator to display all the items of the SortedList object, as shown below.
Sample Code
using System;
using System.Collections;
using System.Collections.Specialized;
class Test
{
static void Main()
{
SortedList sortedList = new SortedList();
sortedList.Add(1, "John Brown ");
sortedList.Add(3, "Alex Smith");
Console.WriteLine("Displaying thenames");
IDictionaryEnumerator en = sortedList.GetEnumerator();
string str = String.Empty;
while (en.MoveNext())
{
str = en.Value.ToString();
Console.WriteLine(str);
}
}
}
Type Safe Collections
Type safe collections are those that comprise of a known type. It would support indexing as an array and has a lot of benefits. A strong typed collection is implemented using any of the following classes.
  1. .CollectionBase
  2. · ReadOnlyCollectionBase
  3. · DictionaryBase
The following are the advantages of using strong typed collections.
  1. · Supports indexing
  2. · Supports enumeration
  3. · Supports dynamic resizing
  4. · Supports serialization
Implementing a Custom Collection Class
The following section shows how we can implement a custom collection class. The following code shows how we can use the "design a custom collection class" by sub-classing the CollectionBase class.

Sample Code

using System;
using System.Collections;
public class Product: CollectionBase
{
public Product this[int index]
{
get
{
return ((Product)(List[index]));
}
set
{
List[index] = value;
}
}
public bool Contains(Product product)
{
return List.Contains(product);
}
public int Add(Product Product)
{
return List.Add(Product);
}
public void Insert(int index, Product product)
{
List.Insert(index, product);
}
public void Remove(Product product)
{
List.Remove(Product);
}
}
The following code shows how we can use the "design a custom collection class" by sub-classing the DictionaryBase class.

Sample Code

using System;
using System.Collections;
public class Product: DictionaryBase
{

public Product this[int index]
{
get
{
return ((Product)(Dictionary[index]));
}
set
{
Dictionary[index] = value;
}
}
public bool Contains(Product product)
{
return Dictionary.Contains(product);
}
public int Add(Product Product)
{
return Dictionary.Add(Product);
}
public void Insert(int index, Product product)
{
Dictionary.Insert(index, product);
}
public void Remove(Product product)
{
Dictionary.Remove(Product);
}
}

Conclusion: Collections in any programming language is the most used programming part in any bussiness problem solutions.

Happy Learning.
If you have any questions please leave me comment .

Subscribe
Posted in Labels: kick it on DotNetKicks.com |

0 comments: