Saturday, January 12, 2013

Collections in .Net

NameSpace: System.Collections
The .NET Framework provides specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
Closely related data can be handled more efficiently when grouped together into a collection. Instead of writing separate code to handle each individual object, you can use the same code to process all the elements of a collection. To manage a collection, use the Array class and the System.Collections classes to add, remove, and modify either individual elements of the collection or a range of elements. An entire collection can even be copied to another collection.
Some Collections classes have sorting capabilities, and most are indexed. Memory management is handled automatically, and the capacity of a collection is expanded as required. Synchronization provides thread safety when accessing members of the collection. Some Collections classes can generate wrappers that make the collection read-only or fixed-size. Any Collections class can generate its own enumerator that makes it easy to iterate through the elements.
Collection types are the common variations of data collections, such as hash tables, queues, stacks, dictionaries, and lists.
Collection Classes have the following properties:-
• Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
• Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.
• Generic collection classes provide increased type-safety and in some cases can provide better performance, especially when they store value types. For more information, see Benefits of Generics (C# Programming Guide). 
The .NET Framework 2.0 introduced the notion of generics. In the .NET Framework 1.x, most of the collection classes stored System.Object references. This meant that every time you extracted an item out of a collection you would have to cast it back to its original type (and if you developed a library, the consumer of that library was required to know what those types were). This cast had a performance impact, especially when storing value types, as adding one to a collection required it first to be boxed into a System.Object and later unboxed when pulled out of the collection and cast back to its original type.
Some Collection Types: Array, ArrayList, Hastable, SortedList, Queue & Stack
Array: 
• The Array class is not part of the System.Collections namespaces. However, it is still a collection because it is based on the IList interface.
• The rank of an Array object is the number of dimensions in the Array. An Array can have one or more ranks.
• Unlike the classes in the System.Collections namespaces, Array has a fixed capacity. To increase the capacity, you must create a new Array object with the required capacity, copy the elements from the old Array object to the new one, and delete the old Array.
• An Array can have multiple dimensions.
• An Array of a specific type (other than Object) has better performance.
ArrayList:
• An ArrayList is a sophisticated version of an array.
• The capacity of an ArrayList is automatically expanded as required.
• ArrayList provide methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time.
HashTable:
• The Hashtable class implement the IDictionary interface. Each element in these collection is a key-and-value pair. A key cannot be null, but a value can be.
• A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, generated using a hash function and based on the key of the element.
• A hash function is an algorithm that returns a numeric hash code based on a key. The key is the value of some property of the object being stored. A hash function must always return the same hash code for the same key. It is possible for a hash function to generate the same hash code for two different keys, but a hash function that generates a unique hash code for each unique key results in better performance when retrieving elements from the hash table.
• Each object that is used as an element in a Hashtable must be able to generate a hash code for itself using an implementation of the GetHashCode method. However, you can also specify a hash function for all elements in a Hashtable by using a Hashtable constructor that accepts an IHashCodeProvider implementation as one of its parameters.
• When an object is added to a Hashtable, it is stored in the bucket that is associated with the hash code that matches the object's hash code. When a value is being searched for in the Hashtable, the hash code is generated for that value, and the bucket associated with that hash code is searched.
SortedList:
• The System.Collections.SortedList class is similar to the Hashtable class implements from the interface IDictionary, but they maintain their elements in sort order by key, and they do not have the O(1) insertion and retrieval characteristic of hash tables.
• Elements are sorted according to an System.Collections.IComparer implementation (for nongeneric SortedList)
• Each class provides properties that return collections containing only the keys or only the values.
Queue:
• Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize.
• The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. The default growth factor is 2.0. The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required.
• Thread Safety: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized method.
• Queue accepts null as a valid value and allows duplicate elements.
Stack: 
• Represents a simple last-in-first-out (LIFO) non-generic collection of objects. tack is implemented as a circular buffer. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
• Stack accepts null as a valid value and allows duplicate elements.
• Thread Safety: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized method.
• Three main operations can be performed on a Stack and its elements:
-Push inserts an element at the top of the Stack.
-Pop removes an element at the top of the Stack.
-Peek returns an element at the top of the Stack but does not remove it from the Stack.


Collections Interfaces:


System.Collections.IEnumerable:
It exposes the enumerator, which provides a collection like behavior to user defined classes. 
Methods:
GetEnumerator() - It returns the enumerator object that can be used to iterate through the collection. It allows using the foreach statement. Enumerators only allow reading the data in the collection.


System.Collections.ICollection:
ICollection interface specifies a method for getting the size of collection, creating enumerators on a collection and managing synchronized access to all non-generic collections. It is a base interface for classes in the System.Collections namespace. 
Properties:
• Count - It returns the number of elements contain by ICollection.
• IsSynchronized - It returns true if access to the ICollection is synchronized.
• SyncRoot - It returns an object that can be used to synchronize access to the ICollection.
Methods:
• CopyTo() - The method copies the elements of the ICollection object to any array, starting at a particular Array index. If .NET is unable to cast source type to destination, then it throws ArrayTypeMismatchException exception.

System.Collections.IList:
IList interface represents the collection of objects that can be individually accessed by index. The implementation of IList falls into three categories: read-only, fixed-size, and variable-size. A read only IList cannot be modified. A fixed size IList does not allow the addition or removal of elements, but it allows the modification of the existing elements. A variables size IList allows the addition, removal, and modification of elements. 
Properties:
• IsFixedSize - It returns true if IList has fixed size.
• IsReadOnly - It returns true if IList is read only.
Methods:
• Add(object value) - It adds the item into the IList.
• Clear() - It removes the all items from the IList.
• Contains(object value) - It returns true if IList contain a specific value. This method uses the Equals and CompareTo methods to determine whether an item exists.
• IndexOf(object value) - It returns the index of a specific item in the IList. This method also uses the Equals and CompareTo methods to determine whether an item exists.
• Insert(int index, object value) - It inserts an item to the IList at specific index. If index equals the number of items in the IList, then value is appended to the end, but if index greater then the number of items in the IList or less then zero, then it throws ArgumentOutOfRangeException exception. If you try to insert item in the read-only or fixed size IList then it throws NotSupportedException exception.
• Remove(object value) - It removes the first occurrence of a specific object from the IList. If you try to remove value from read only or fixed size IList, then it throws NotSupportedException.
• RemoveAt(int index) - It removes an item at the specified index. It throws ArgumentOutOfRangeException exception for invalid index in list and throws NotSupportedException exception for read only and fixed size IList.

System.Collections.IDictionary:
It represents a collection of key/value pairs. IDictionary interface is implemented by classes that supports collections of associated keys and values. Each element in a key/value pair is stored in a DictionaryEntry object. It allows the contained keys and values to be enumerated, but it does not imply any particular sort order.
Properties:
• IsFixedSize - It returns true if IDictionary object has a fixed size.
• IsReadOnly - It returns true if IDictionary object is read only.
• Keys - It returns ICollection object containing keys of the IDictionary object.
• Values - It returns ICollection object containing values of the IDictionary object.
Methods:
• Add(object key, object value) - Adds an element with the specified key and value into the IDictionary object.
• Clear() - It removes all elements from the IDictionary object.
• Contains(object key) - It returns true if IDictionary object contains an element with the specified key.
• GetEnumerator() - It returns an IDictionaryEnumerator object for the IDictionary object.
• Remove(object key) - It removes the element with the specified key from the IDictionary object.

11 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    java training in chennai | java training in bangalore

    java training in tambaram | java training in velachery

    java training in omr

    ReplyDelete
  3. Outstanding blog post, I have marked your site so ideally I’ll see much more on this subject in the foreseeable future.
    python online training
    python training in OMR
    python training course in chennai

    ReplyDelete
  4. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    Devops Training in pune
    DevOps online Training

    ReplyDelete

  5. Nice post, Thanks for sharing for more information about .net collections..check it once at
    aws online training
    aws training in hyderabad
    aws online training in hyderabad

    ReplyDelete
  6. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    ReplyDelete
  7. Wonderful article.
    Thanks for sharing this.
    TezLyrics

    ReplyDelete