Saturday, 16 April 2016

Collections

What is Collections?

.NET framework provides specialized classes for data storage and retrieval, i.e Arrays. Collections are enhancement to the arrays.

There are two distinct collection types in C#. The standard collections, which are found under the System.Collections namespace and the generic collections, under System.Collections.Generic. The generic collections are more flexible and are the preferred way to work with data. The generic collections or generics were introduced in .NET framework 2.0. Generics provides enhance to code reuse, type safety, and performance.

Some of Standard Collections types:

ArrayList:

An ArrayList is a collection from a standard System.Collections namespace. It is a dynamic array. It provides random access to its elements. An ArrayList automatically expands as data is added. Unlike arrays, an ArrayList can hold data of multiple data types. ArrayList implements the IList interface using an array and very easily we can add , insert , delete , view etc. It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink. Elements in the ArrayList are accessed via an integer index. Indexes are zero based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. Inserting or deleting an element in the middle of the dynamic array is more costly. It takes linear time. It accept object value, so it is not type safe.

Defining an ArrayList:

ArrayList objArrayList = new ArrayList();

Adding, Insertion, Removing and Sorting records in ArrayList:

Add : Add an Item in an ArrayList

objArrayList.Add("Item - 1"); // It accept object value to Add, so It is not type safe.

Insert : Insert an Item in a specified position in an ArrayList

objArrayList.Insert(4, "Item - 4"); // First argument is index and second argument is actual value (object type)

Remove : Remove an Item from ArrayList

objArrayList.Remove("Item - 1"); // Remove first item from objArrayList.

RemoveAt: Remove an item from a specified position from ArrayList

objArrayList.RemoveAt(1); // Remove item at position 1 (index 1) from objArrayList.
Sort : Sort Items in an ArrayList

objArrayList.Sort(); // Sort objArrayList item in Ascending Order.

Hashtable:

Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the Generic Dictionary type. Hashtable is normally used when huge records are comes up for insertion (for fast insertions of these records).


Defining an Hashtable:

Hashtable objHashtable = new Hashtable();

Example:


objHashtable.Add(10, "Ansar"); // First argument is Obj key, second element obj value (key and value pair)
            objHashtable.Add(20, "Aftab");
            objHashtable.Add(30, "Nadeem");

            objHashtable.Add(40, "Ghazanfar");


// Display the keys.
            foreach (int key in objHashtable.Keys)
            {
                Console.WriteLine(key);
            }

            // Display the values.
            foreach (string value in objHashtable.Values)
            {
                Console.WriteLine(value);

            }

Output:

(First loop)
10       
20
30
40
(Second loop)
Ansar
Aftab
Nadeem
Ghazanfar
What are Generics?
Generics were first introduced into the C# language in .NET 2.0. They provide a type-safe method of accessing data used in collections and/or function calls. Using Generics significantly decreases the amount of run-time errors due to casting or boxing/unboxing because the types used in a generic operations are evaluated at compile time. If you are a C++ fan, you will realize that Generics operate in a very similar way to Template Classes in C++, but with a few differences.
What is the Difference between C++ Templates and C# Generics?
One of the main differences between C++ Template Classes and C# Generics is that in C#, you cannot use arithmetic operators (except custom operators) in a generic class.
C# does not allow type parameters to have default types, nor does C# allow you to use the type parameter (T) as the base class for the Generic type.
These are only a few of the differences at a glance, but it is important to take note of them if you are coming from a familiar C++ frame of reference. Even though C++ is more flexible in this area, the C# model provides a decreased amount of runtime errors by limiting what can be done based on Generic Constraints.

Some of Generics types:

List:

List class is a collection and defined in the System.Collections.Generic namespace and it provides the methods and properties like other Collection classes such as add, insert, remove, search etc. The C# List < T > class represents a strongly typed list of objects that can be accessed by index and it supports storing values of a specific type without casting to or from object. List normally use for reading data quickly.

Example:


List<int> lstOfInt = new List<int>();
lstOfInt.Add(1);
lstOfInt.Add(2);
lstOfInt.Add(3);
lstOfInt.Add(4);

foreach (int item in lstOfInt)
{
   Console.WriteLine(item);
}

List<string> lstOfString = new List<string>();
lstOfString.Add("Ghazanfar");
lstOfString.Add("Ali");
lstOfString.Add("Ghazi");

foreach (string item in lstOfString)
{
  Console.WriteLine(item);


}

Dictionary:

Dictionary in C# is a generic. We specify its types with a special syntax. It is an updated Hashtable. Dictionary based on the key value pair. It is normally use for fast insertion and deletion if the records are comparatively less.


Example:

Dictionary<string, int> myDictionary = new Dictionary<string, int>(){
{"ajmal", 2},
{"ali", 1},
{"ghazi", 0},
{"zafar", -1}
};

// Loop over dictionary with foreach.
foreach (KeyValuePair<string, int> pair in myDictionary)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
// Use var keyword to enumerate dictionary.
foreach (var pair in myDictionary)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);

}

Queue:

Serving the first request that comes first. First-in-First-out (FIFO) mechanism. For example serving the client that first comes to your application.

How to declare a Queue:


Queue queMonths = new Queue();
OR
Queue<string> queMonths = new Queue<string>();

Enqueue : Add an Item in Queue


queMonths.Enqueue("January");
queMonths.Enqueue("February");


queMonths.Enqueue("March");

Peek   : Get the reference of the oldest item 

queMonths.Peek() //Getting January

Dequeue : Remove the oldest item from Queue

queMonths.Dequeue(); //Removing first element from queMonths (Removing January)

Stack:

Stack is a LIFO collection. Serving the last request that comes up. Last-in-First-out mechanism based.

How to declare a Stack:

Stack stack = new Stack();
OR
Stack<int> stackInt = new Stack<int>();

Push : Add an Item in Stack
stackInt.Push(10);
stackInt.Push(100);
stackInt.Push(1000);

Peek   : Get the last element inserted 

stackInt.Peek();

Pop : Pop the last element inserted
stackInt.Pop();



(Practice Makes a Man Perfect)

No comments: