Friday, January 31, 2014

C# Data Structures Under One Roof

C# Data Structures Under One Roof
In this article I am trying to explain C# data structures while programming.I have written the theory in the commented form.
Just go step by step you will get understand better with theory.
class Empty
{}
static void Main(string[] args)
{
#region Collections

/*=================ArrayList - Start====================*/
/*Introduction: 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 enhance code reuse, type safety, and performance. */

/*ArrayList => An ArrayList is a collection from a standard System.Collections namespace.
It is a dynamic array.An ArrayList automatically expands when data is added.
ArrayList can hold data of multiple data types.*/

ArrayList da = new ArrayList();
da.Add("Visual Basic");
da.Add(344);
da.Add(55);
da.Add(new Empty());
da.Remove(55);

Console.WriteLine("ArrayList - output");
foreach (object el in da)
{
Console.WriteLine(el);
}

/*Output => Visual Basic
344
YourParentClassName+Empty*/
/*=================ArrayList - End====================*/
/*=================List - Start====================*/
/*Introduction: A List is a strongly typed list of objects that can be accessed by index.
It can be found under System.Collections.Generic namespace. */

// Use the List type.
List<string> list = new List<string>();
list.Add("dotnet");
list.Add("ilyas");
list.Add("removeme");
list.Insert(1, "developer"); //You can insert the value at specific location
list.Sort(); //It sort list collection in ascending order
list.Remove("removeme");

Console.WriteLine();
Console.WriteLine("List - output");
/*You can read the list in this way*/
foreach (string element in list.OrderByDescending(i => i))    //show in descending
{
Console.WriteLine(element);
}

/*Output => ilyas
dotnet
developer*/
/*=================List - End====================*/
/*=================Linked List - Start====================*/
/*Introduction:LinkedList only allows sequential access.
LinkedList allows for constant-time insertions or removals,
but only sequential access of elements.*/

LinkedList<int> nums = new LinkedList<int>();

nums.AddLast(13);
nums.AddLast(44);
nums.AddLast(53);
nums.AddLast(21);
nums.AddLast(7);
nums.AddFirst(10);
nums.AddFirst(17);

LinkedListNode<int> node = nums.Find(7); //We can find the specific element
nums.AddBefore(node, 5);//add the element before

Console.WriteLine();
Console.WriteLine("LinkedList - output");
foreach (int num in nums)
{
Console.WriteLine(num);
}

/*Output => 17
10
13
44
53
21
5
7*/
/*=================Linked List - End====================*/
/*=================Dictionary - Start====================*/
/*Introduction:Dictionary stores the values with key value pair,
You can read the dictionary value with a key in this way,
it is also called as associative array,
it is very fast but takes more space since we have each key with each value*/

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 1);
dictionary.Add("dog", 4);


Console.WriteLine();
Console.WriteLine("Dictionary - output");
var keys = new List<string>(dictionary.Keys);
foreach (string key in keys)      //Reading values with key
{
Console.WriteLine(dictionary[key]);
}


var values = new List<int>(dictionary.Values);
foreach (int val in values)//Reading keys with value
{
/*Accessing thi way lead to an error => Console.WriteLine(dictionary[val]);*/
var myValue = dictionary.FirstOrDefault(x => x.Value == val).Key; //this way you can read key with value
Console.WriteLine(myValue);
}

foreach (KeyValuePair<string, int> kvp in dictionary) //Reading key value pair
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
/*Output: 1
4
cat
dog
Key = cat, Value =1
Key = dog, Value =4 */

/* In the similar there is called Hashtable which is Collection type not generic.
Ex:          
               Hashtable hashtable = new Hashtable(); 
                     hashtable.Add("Area", 1000);
                     hashtable.Add("Perimeter", 55);
                     hashtable.Add("Mortgage", 540);
Accessing:
                Hashtable hashtable = GetHashtable();
               Console.WriteLine(hashtable.ContainsKey("Perimeter"));o/p - True
                Console.WriteLine(hashtable.Contains("Area")); o/p - True
                Console.WriteLine((int)hashtable["Area"]); o/p - 100

The major differences between HashTable and Dictionary are
1. Hashtable is threadsafe and while Dictionary is not.
2. Dictionary is types means that the values need not to boxing while Hashtable
    values need to be boxed or unboxed because it stored the values and keys as
    objects.        
3. When you try to get the value of key which does not exists in the collection, the
    dictionary throws an exception of 'KeyNotFoundException' while hashtable returns
    null value.
4. When using large collection of key value pairs hashtable would be considered more
    efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order
    of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.
Note: I am not taken its output in command prompt.*/
/*=================Dictionary - End====================*/
/*=================Queues - Start====================*/
/*Introduction: A queue is a First-In-First-Out (FIFO) data structure.
The first element added to the queue will be the first to be removed.*/
Queue<string> msgs = new Queue<string>();

msgs.Enqueue("Msg-1");
msgs.Enqueue("Msg-2");
msgs.Enqueue("Msg-3");
msgs.Enqueue("Msg-4");

Console.WriteLine();
Console.WriteLine("Queue - output");
//Dequeue() removes and returns the item at the beginning of the queue.
Console.WriteLine(msgs.Dequeue() + " =>Dequeue() removed first item" + "\n");


// Peek() method returns the next item from the queue, but does not remove it from collection
Console.WriteLine(msgs.Peek() + "=>Peek() returned next item" + "\n");

Console.WriteLine("Now msgs Queue has below elements");
foreach (string msg in msgs)
{
Console.WriteLine(msg);
}
/*Output-    
Msg-1 =>Dequeue() removed first item

Msg-2  =>Peek() returned next item

Now msgs Queue has below elements
Msg-2
Msg-3
Msg-4 */

/*=================Queues - End====================*/
/*=================Stacks - Start====================*/
/*Introduction: A stack is a Last-In-First-Out (LIFO) data structure.
The last element added to the queue will be the first  to be removed. */

Stack<int> stk = new Stack<int>();

stk.Push(1);
stk.Push(2);
stk.Push(3);
stk.Push(4);

Console.WriteLine();
Console.WriteLine("Stack - output");
Console.WriteLine(stk.Pop() + " - Pop() method removes the last one" + "\n");
Console.WriteLine(stk.Peek() + " - Peek() method returns item from stack top but does not remove it. " + "\n");

Console.WriteLine();

Console.WriteLine("Now stk stack has below elements");

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

/*Output-
4 - Pop() method removes the last one
3 - Peek() method returns item from stack top but does not remove it.

Now stk stack has below elements
3
2
1
*/
/*=================Stacks - End====================*/
Console.Read();
#endregion


}

Output Window:

Difference between Generics & Collections:
Generics provides the type safe code with re-usability like as algorithm. In algorithms such as sorting, searching,  comparing etc. you don’t specify what data type(s) the algorithm operates on. The algorithm can be operates with any types of data. In the same way Generics operate, you can provide different data type to Generics. For example, a sorting algorithm can operates on integer type, decimal type, string type, DateTime type etc.
In-Details reference link  about this difference is here.
You can comment about it below.

No comments: