RSS

Collections in C# !!

20 Jan

collections

A collection is a type that aggregates objects; it acts as a container for a set of objects. You can create an instance of a collection class and add objects to the collection. You can then access those items by using methods that the collection class provides. Collection classes may appear to be similar to arrays, but, in fact, a collection class serves a different purpose to an array and in most circumstances is much more flexible.

When you define an array, you specify the type of data that the array stores and the size of the array. An array is type-safe, but has a big limitation; when you define an array, you must specify how many items the array can hold. This quantity may not be easy to determine in advance. If you specify too large an array, you will use too much memory; if you specify too small an array, you will run out of space. Arrays work well when you know exactly how many values you need to store.

Collections are much more flexible. When you create an instance of a collection class, you do not need to specify the size of the collection. The collection dynamically grows and shrinks according to the volume of data that it stores. This dynamic space management makes collections very powerful; if you used arrays instead of collections and needed the array to resize, you would need to write significantly more code to manage the array size. The disadvantage of arrays is the overhead that is associated with performing dynamic memory management. However, you can mitigate this overhead to some extent when you initialize an array; you can specify an initial size that should match the most common requirements for your application.

Object Types in Collections

When you use an array to store several objects, you explicitly specify the type of the data that you want to store in the array. For example, you may have an array of integers or an array of strings. When you store values in the array, or retrieve a value from the array, it is strictly type-safe. If you attempt to store or retrieve data of the wrong type, the compiler detects this problem and fails with an error.

When you use a collection, you do not specify the type of data to store. The collection classes store references to other objects by using the System.Object type. This feature enables you to construct collections that store mixed types; for example, you can store string objects and int values in the same collection. When you retrieve an item from the collection, you must cast the item to the appropriate type.

Dimensions in Collections and Arrays

When you define an array, you can specify that it has more than one dimension. Collections do not have dimensions. However, you can imitate a multidimensional collection by storing collections in a collection.

Using Collection Classes

The .NET Framework defines a set of collection classes in the System.Collections namespace. Most collections have some similarities; they all implement the ICollection interface. This interface defines a small number of methods and properties, including:

  • CopyTo. This method enables you to copy the contents of a collection to an array.
  • GetEnumerator. This method returns an object called an enumerator that you can use to iterate through the items in the collection.
  • Count. This is a property that indicates the current number of items in the collection.

Some collections also implement the IList interface. This interface defines members that enable you to access the elements in the collection by using array-like notation, in addition to adding and removing members by using methods called Add and Remove.

In addition to the members that the ICollection and IList interfaces require, most collection classes expose specific methods and members that underpin their functionality. The names for these methods are not restricted and are normally closely related to the purpose of the collection. For example, the Queue class exposes Enqueue and Dequeue to add and remove items from the queue in a first-in, first-out (FIFO) manner. The Stack class provides Push and Pop methods to enable you to add items in a first-in, last-out (FILO) manner.

The collection classes in the System.Collections namespace store System.Object objects, rather than objects of a more specific type. You can add any object to a collection class, but when you retrieve an object from a collection, you must cast the object to its correct type before you can use all of the members that the object exposes. If you attempt to cast an object in a collection to the wrong type, your application will throw an InvalidCastException exception.

Warning: You should exercise caution when you retrieve objects from a collection to ensure that you cast the objects correctly. Avoid adding objects of different types to the same collection wherever possible.

The following code example shows how to use the ArrayList class (a simple collection class that implements an array that can dynamically resize itself). The ArrayList class implements the IList interface. It provides the Add method that you can use to add an object to the end of the collection, and the RemoveAt method that you can use to delete an item from the collection at a specified position. You can also use the Remove method to search through the collection and delete the first occurrence of a specified item from the collection. As you add items, the collection can grow automatically.

// Create a new ArrayList object.
ArrayList list = new ArrayList();

// Add items to the ArrayList collection.
list.Add(3);
list.Add(4);
list.Add(6);

// Add a string to the ArrayList collection.
// The ArrayList stores objects, not specific
// types so you can add any type to the collection.
list.Add("String Object");

// Remove an object from the ArrayList collection
// by specifying the object to remove.
list.Remove(6);
// Remove an object from the ArrayList collection
// by specifying the index from which to remove the item.
list.RemoveAt(1);

// Use an indexer to access a specific item in the 
// collection. Cast the object to its correct type.
int temp = ((int)list[0]) * 5;

Common Collection Classes

The System.Collections namespace contains several general-purpose collection classes. Each of these collection classes is optimized to implement a specific mechanism for aggregating and accessing data.

  • The ArrayList Collection Class

The ArrayList collection class is similar to an array. You can add items to the array and retrieve items by using a zero-based index.

The ArrayList class dynamically increases in size as you add values to the collection. You can use the Capacity property to get or set the current size of the collection. The ArrayList class does not automatically shrink when you remove items from the collection. If you remove a significant number of items from the collection, you can use the TrimToSize method to reduce the size of the collection, or alternatively, you can set the Capacity property to a lower value.

The following code example shows a simple use of the ArrayList class.

// Create a new ArrayList object.
ArrayList al = new ArrayList();

// Add values to the ArrayList collection.
al.Add("Value");
al.Add("Value 2");
al.Add("Value 3");
al.Add("Value 4");

// Remove a specific object from the ArrayList collection.
al.Remove("Value 2"); // Removes "Value 2"

// Remove an object from a specified index.
al.RemoveAt(2); // Removes "Value 4"

// Retrieve an object from a specified index.
string valueFromCollection = (string)al[1]; 
// Returns "Value 3"
  • The Queue Collection Class

The Queue class is a FIFO data structure. Rather than expose Add and Remove methods, the Queue class exposes Enqueue and Dequeue methods. When you use the Enqueue method on an object, it is automatically added to the end of the collection; when you use the Dequeue method on an object, it is automatically removed from the start of the collection. You can also use the Peek method to retrieve the first item in the queue without removing it.

The Queue class grows automatically as objects are added to the collection. If you need to recover memory from the Queue object, by reducing the size of the collection, you can use the TrimToSize method.

The following code example shows a simple use of the Queue class.

// Create a new Queue object.
Queue queue = new Queue();

// Add values to the Queue collection.
queue.Enqueue("Value");
queue.Enqueue("Value 2");
queue.Enqueue("Value 3");
queue.Enqueue("Value 4");

// Retrieve an object from the Queue collection.
string valueFromCollection = (string)queue.Dequeue();
// Returns "Value"
  • The Stack Collection Class

The Stack class is a FILO data structure. The Stack class exposes Push and Pop methods to add and remove items. When you use the Push method to add an object to a Stack collection, the object is added to the start of the collection; when you use the Pop method on an object, it is automatically removed from the start of the collection and returned. Like the Queue class, the Stack class provides the Peek method to return the item at the start of the Stack collection without removing it.

The Stack class grows automatically as objects are added to the collection. If you need to recover memory from the Stack object, by reducing the size of the collection, you can use the TrimToSize method.

The following code example shows a simple use of the Stack class.

// Create a new Stack object.
Stack stack = new Stack();

// Add values to the Stack collection.
stack.Push("Value");
stack.Push("Value 2");
stack.Push("Value 3");
stack.Push("Value 4");

// Retrieve a value from the Stack collection without 
// removing it from the Stack collection.
string peekValueFromCollection = (string)stack.Peek();
// Returns "Value 4"

// Retrieve an object from the Stack collection.
string valueFromCollection = (string)stack.Pop();
// Returns "Value 4"

// Retrieve another object from the Stack collection.
string valueFromCollection2 = (string)stack.Pop();
// Returns "Value 3"
  • The Hashtable Collection Class

The Hashtable class enables you to store key and value pairs in a rapid access collection. When you add an item to a Hashtable class by using the Add method, you must provide both a key and a value. The key must be unique in the collection, but the value can be a duplicate. The Hashtable class stores objects based on the hash value of the key.

You retrieve a value from a Hashtable class by using an indexer and specifying the key of the value that you want to retrieve. The Hashtable class hashes the key to identify the location of the required value. The Hashtable class is significantly faster than other collections for retrieving an item from a large collection because it searches fewer items to locate the correct value. However, for smaller collections, the overhead of generating a hash every time you add a value to the collection can actually reduce the performance of your application. Therefore, for smaller collections, you should consider using another collection class.

The Hashtable class relies on creating hashes of values that are added to the collection; for this reason, you can only add keys to the collection where the type of the key implements the GetHashCode method. Every object includes a default implementation of the GetHashCode method, which is inherited from the System.Object class. However, you may often need to add a more complex hashing algorithm to any types that you develop. When you develop a hashing algorithm for use with a Hashtable collection class, you should use a case-insensitive algorithm.

The following code example shows a simple use of the Hashtable class.

// Create a new Hashtable object.
Hashtable hashtable = new Hashtable();

// Add values to the Hashtable collection.
hashtable.Add("Key A", "Value");
hashtable.Add("Key B", "Value 2");
hashtable.Add("Key C", "Value 3");
hashtable.Add("Key D", "Value 4");

// Remove an item from the Hashtable collection by specifying the key.
hashtable.Remove("Key C");

// Retrieve an item from the Hashtable collection by specifying the key.
string valueFromCollection = (string)hashtable["Key B"];
// Returns "Value 2"
  • The SortedList Collection Class

Like a Hashtable class, the SortedList collection class stores a collection of key/value object pairs. However, values in the collection are sorted by using the key. If you iterate through the data in a SortedList collection, the data will be presented in key order.

The following code example shows a simple use of the SortedList class.

// Create a new SortedList object.
SortedList sortedList = new SortedList();

// Add values to the SortedList collection.
sortedList.Add("Key A", "Value");
sortedList.Add("Key B", "Value 2");
sortedList.Add("Key C", "Value 3");
sortedList.Add("Key D", "Value 4");

// Remove an item from the SortedList by specifying the key.
sortedList.Remove("Key C");

// Retrieve an item from the SortedList collection 
// by specifying the key.
string valueFromCollection = (string)sortedList["Key B"];
// Returns "Value 2".

// Retrieve an item from the SortedList collection 
// by specifying the index.
string valueFromCollection2 = (string)sortedList.GetByIndex(0);
// Returns "Value".
 
Leave a comment

Posted by on January 20, 2013 in Visual C# . NET

 

Tags: , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: