C# Queue

c# queue explained, definition, examples.

In my last post you can find explanation of Stack Collection. Concept of both collections is similar.

Queue is a FIFO(first-in, first out) collection of objects. It’s generic type that is part of  System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class:Enqueue(Object),Dequeue(),Peek(). First lets explain the FIFO concept.

queue-line_2991665

 

Queue line can be a good, real world example of FIFO concept. Person who will stand in line first will be served first. Using this concept we can enqueue the items into a queue and get it in the same order. Let’s move on to class syntax.

 

Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.

Queue<int> queue = new Queue<int>();

 

Let’s look at the methods

 Enqueue(Object)

class Program
{
    static void Main()
    {
	Queue<int> queue = new Queue<int>();
	queue.Enqueue(1);
	queue.Enqueue(2);
	queue.Enqueue(3);
	queue.Enqueue(4);
}
}

We crate new queue and by using Enqueue() method  we add new items to the collection.  Simple as that

Dequeue()

Removes the object at the beginning of your Queue. The algorithmic complexity of this is O(1). It doesn’t loop over elements.

queue.Dequeue();

this method doesn’t take any parameters

Peek()

This method works the same way as in stack. It returns the value without removing it. In this case first value in queue.

queue.Peek();

 

This is not the most popular type of collections, but it can be useful for creating things like for example, player turn system in strategy game. In next post I’ll cover another type of collection, bitArray. Stay Awesome!

 

C# Stack

stack collection in c#

Stack is a LIFO(last-in, first out) collection of objects. It’s generic type that is part of  System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class: Peek(),Pop(),Push(). First lets explain the LIFO concept.

1872-plates-pile

 

Great example of LIFO visualization is a stack of plates. When new plate is added its stored on the top of the stack, and when we want to remove a plate we can only grab the top one. Same idea is used in programming. Using this concept we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.Now lets see the class syntax and implementations of the methods.

Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.

 Stack<string> numbers = new Stack<string>();

Let’s look at the methods

Push()

First we need to add items to our stack, to do this we will use Push() method

class Program
{
    static void Main()
    {
	Stack<int> stack = new Stack<int>();
	stack.Push(1);
	stack.Push(2);
	stack.Push(3);

	foreach (int i in stack)
	{
	    Console.WriteLine(i);
	}
    }
}

Output:

3

2

1

 

Push method adds elements to he top of the stack, elements are printed in reverse order.

Pop() and Peek()

when we have elements in our stack we can now return them with Pop() method, this will delete item from stack. If we want to copy the value, leaving it on the top of the stack we use Peek() method.

static void Main()
    {
	int pop = stack.Pop();
	Console.WriteLine(pop);

	int peek = stack.Peek();
	Console.WriteLine("Element at the top:");
	Console.WriteLine(peek);
    }

Output:

3

Element at the top:2

Now you can add and remove items from stack.  Stack can be useful for simulating for example deck of cards. In next article I’ll cover similar type called queue. Stay Awesome!

Hashtable

introduction to hashtable in c# .net

Hashtable is part of System.Collection namespace. You can read more about collections here. The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. A hash table is made up of a mapping function and an array. It uses the key to access the elements in the collection. The mapping function is used to assign numerical values (keys) to the data. This helps in categorizing the data, which speeds up search times when you search for it. Hashtable is an older .NET Framework type. It is slower than the generic Dictionary type. In hashtable we don’t declare type of the object with it signature.

Lest crate an example of hashtable.

 static void Main()
    {
                Hashtable hashtable = new Hashtable();
                hashtable[1] = "John";
                hashtable[4] = "Mike";
                hashtable[7] = "Bob";
    }

We can use class constructor to crate empty table, and than assign values to the selected index.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be. DictionaryEntry  defines a dictionary key/value pair that can be set or retrieved. DictionaryEntry have two properties value and key. We can use this structure to loop through all objects in the table.

 foreach (DictionaryEntry entry in hashtable)
        {
              Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
        }

 

We can use conditions to check the data status before performing an action

public virtual bool ContainsKey(object key);

 

Hashtables are much more efficient than most other search trees when it comes to finding data. They are used in all kinds of computer software – especially database software.

We can use method like Add() or Remove() function to manipulate data in easy to understand way.

	hashtable.Add(1, "Sandy");
	hashtable.Add(2, "Bruce");

 

This was just an introduction to the subject, hash table is more complex subject that involves many rules like that the hash function should assign unique keys to each data slot, but in practice a pair of keys might get hashed to the same table. This is called collision. There are two ways of dealing with it. I’ll describe both of them in next post.

 

 

 

Collections

introduction to collections in C# .NET

In last post I wrote about implementation of generics, and the difference between list and an array. Today we will take closer look at Collections. This is more general subject, mentioned earlier generics are part of System.Collection class.

Collections are used to group objects and simplify the process off adding, removing and manipulating data. Collections are a very good alternative of arrays. To see the difference we need to look at the arrays first. Let’s take an example, this array is storing object of simple class called Student.

Here is our Student Class

public class Student
 {
 public int ID { get; set; }
 public string Name { get; set; }
 public string Grade { get; set;}
 }

now we create few instances, like this one

 Student student1 = new Student()
 {
 ID = 123,
 Name = "John",
 Grade = "A"
 };

We will use those data for other examples as well.

Array of objects will look like this

Student[] arrayOfStudents = new Student[3];
 arrayOfStudents[0] = student1;
 arrayOfStudents[1] = student2;
 arrayOfStudents[2] = student3;

now let’s say that we want to ad another student to our class. can we just write

arrayOfStudents[3] = student4;

Answer is, No. Writing this we will not have any syntax errors, but our program will crash. Adding new items is just one example of how not flexible arrays are. Imagine you have to remove item and  than shift all indexes. Here’s  where collections really shine.

Array List

What is an ArrayList? In post about generics we analysed collection List<>. So what’s the difference between generic List<> and ArrayList?

ArrayList is part of System.Collections namespace, while List<> is inherent from System.Collections.Generics. ArrayList was part of earliest version of .NET, and it can store objects of different type like string and integer together.

ArrayList newlist = new ArrayList();
 newlist.Add(10);
 newlist.Add(36);
 newlist.Add("John");

This can cause many problems for example while we iterating through our array and we want to compare the  value with a number.

That’s why with Generic List<> we have declared type of the stored variables while we crating our list.

Basic Collections methods

Lets go back to previous example. This time lets use ArrayList insted

 ArrayList listOfStudents = new ArrayList();
 listOfStudents.Add(student1);
 listOfStudents.Add(student2);
 listOfStudents.Add(student3);

now we can simply add new students, by using Add method

 listOfStudents.Add(student4);

in similar way we can remove the object, by using Remove()

listOfStudents.Remove(student3);

Those are just simplest and most basic methods. List of full documentation you can find here .

One more interesting feature. You can convert Array into ArrayList, and reverse. To convert ListArray into array just use, in this example:

ArrayList newListOfStudents = new ArrayList(arrayOfStudents);
//Print data to make sure it works properly
 Console.WriteLine(newListOfStudents.IndexOf(student3));

In next part we will analyse other types of collections like Hash Tables, Binary Trees or Stacks. And we will see how to use properties of keys. Stay Awesome!