Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Sorted List - Generic

C# Sorted List

In c#, SortedList is a generic type of collection and it is used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

By default, the sortedlist will sort a key/value pairs in ascending order of the key and the sortedlist will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

In c#, the sortedlist will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so you can add or remove elements from the sortedlist based on our application requirements.

C# includes two type of SortedList, generic SortedList and non-generic SortedList. Generic SortedList denotes with angel bracket: SortedList<TKey,TValue> where TKey is for type of key and TValue is for type of value. Non-generic type do not specify the type of key and values.


You can instantiate SortedList<TKey, TValue> by specifying type for key and value, as shown below.

Ex. SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();


Properties


 Property     Description
 Capacity     Gets or sets the number of elements that the SortedList<TKey,TValue> can store 
 Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
 IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
 Keys Get list of keys of SortedList<TKey,TValue>
 Values Get list of values in SortedList<TKey,TValue>.


Method

 Method         Description
Add  Add key-value pairs into SortedList<TKey, TValue>.
Remove Removes element with the specified key.
Remove At Removes element at the specified index.
Contains Key Checks whether the specified key exists in SortedList<TKey, TValue>.
Contains Value Checks whether the specified key exists in SortedList<TKey, TValue>.
Clear Removes all the elements from SortedList<TKey, TValue>.
Index Of Key Returns an index of specified key stored in internal array of SortedList<TKey, TValue>
Index Of Value
 Returns an index of specified value stored in internal array of SortedList<TKey,   TValue>
Try Get Value Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 class CollectionExamples
    {
        public static void Main(String[] args)
        {

            SortedList<int, string> sl = new SortedList<int, string>();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }


Queue(Non Generic)

Queue:

C# includes a Queue collection class in the System.Collection namespace. Queue stores the elements in FIFO style (First In First Out), exactly opposite of the Stack collection. It contains the elements in the order they were added.

Queue collection allows multiple null and duplicate values.

Use the Enqueue() method to add elements into Queue

The Dequeue() method returns and removes elements from the beginning of the Queue. Calling the Dequeue() method on an empty queue will throw an exception.

The Peek() method always returns top most element.


Properties of queue

Count - Returns the total count of elements in the Queue.

Methods of queue

  1. Enqueue: Adds an item into the queue.
  2. Dequeue: Removes and returns an item from the beginning of the queue.
  3. Peek: Returns an first item from the queue
  4. Contains: Checks whether an item is in the queue or not
  5. Clear: Removes all the items from the queue.
  6. TrimToSize: Sets the capacity of the queue to the actual number of items in the queue.



1.Enqueue: Enqueue method is used to add element in queue.you can add element of any datatype as it's a non-generic collection.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null

            foreach(var item in _queue)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadLine();
        }
    }

2.Dequeue: 
Dequeue() method is used to retrieve the top most element in a queue collection.

Dequeue() removes and returns a first element from a queue because the queue stores elements in FIFO order.
 
Calling Dequeue() method on empty queue will throw InvalidOperation exception. So always check that the total count of a queue is greater than zero before calling the Dequeue() method on a queue.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine("Length Before Dequeue {0}", _queue.Count);
           Console.WriteLine("Calling Dequeue {0}", _queue.Dequeue()); //Return first element and remove it.
           Console.WriteLine("Length After Dequeue {0}", _queue.Count);

            Console.ReadLine();
        }
    }

Output:

Length Before Dequeue 5
Calling Dequeue 1
Length After Dequeue 4


3. Peek() : The Peek() method always returns the first item from a queue collection without removing it from the queue. 

Calling Peek() and Dequeue() methods on an empty queue collection will throw a run time exception "InvalidOperationException".

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine("Length Before Dequeue {0}", _queue.Count);
           Console.WriteLine("Calling Dequeue {0}", _queue.Peek()); //Return first element
           Console.WriteLine("Length After Dequeue {0}", _queue.Count);

            Console.ReadLine();
        }
    }

Output

Length Before Dequeue 5
Calling Dequeue 1
Length After Dequeue 5


4.Contains()
The Contains() method checks whether an item exists in a queue. It returns true if the specified item exists; otherwise it returns false.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine(_queue.Contains(1)); // it will return true
        

            Console.ReadLine();
        }
    }


5.Clear() :The Clear() method removes all the items from a queue.

Example

 static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null

            _queue.Clear();
           Console.WriteLine(_queue.Count);//it will return 0
        

            Console.ReadLine();
        }

Stack(Non generic)

C# Stack

C# includes a special type of collection which stores elements in LIFO style (Last In First Out).

Stack allows null value and also duplicate values. It provides a Push() method to add a value and Pop() or Peek() methods to retrieve values.

Use the Push() method to add elements into Stack.

The Pop() method returns and removes elements from the top of the Stack. Calling the Pop() method on the empty Stack will throw an exception.

The Peek() method always returns top most element in the Stack.

Properties

Count- Return the total count of element in the stack.

Method

  1. Push: Inserts an item at the top of the stack.
  2. Peek: Returns the top item from the stack.
  3. Pop: Removes and returns items from the top of the stack.
  4. Contains: Checks whether an item exists in the stack or not.
  5. Clear: Removes all items from the stack.

1. Push: The Push() method adds values into the Stack. It allows value of any datatype

Example:

  static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);

            foreach (var item in _stack)
            Console.WriteLine(item);
            Console.ReadLine();

        }

2.Peek: The Peek() method returns the last (top-most) value from the stack. Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method.

The below program return 4 as an output.

Example
class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            Console.WriteLine(_stack.Peek());
            Console.ReadLine();

        }
    }

3.Pop(): You can also retrieve the value using the Pop() method. The Pop() method removes and returns the value that was added last to the Stack. The Pop() method call on an empty stack will raise an InvalidOperationException. So always check for number of elements in stack must be greater than 0 before calling Pop() method.

Below program retrurn 3,2 and  1 as an output.
Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            _stack.Pop();
            foreach (var item in _stack)
                Console.WriteLine("items {0}", item);
            Console.ReadLine();

        }
    }
    
4.Contains():The Contains() method checks whether the specified item exists in a Stack collection or not. It returns true if it exists; otherwise it returns false.

Below program return true as an output.

class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            Console.WriteLine("Is Exist : {0}", _stack.Contains(1));
            Console.ReadLine();
        }
    }


5.Clear() :The Clear() method removes all the values from the stack.

class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);

           _stack.clear();
            Console.WriteLine("Total {0}",_stack.count);
            Console.ReadLine();
        }

Array List

What is Array List?

ArrayList is a non-generic type of collection in C#. It can contain elements of any data types. It is similar to an array, except that it grows automatically as you add items in it. Unlike an array, you don't need to specify the size of ArrayList.

the ArrayList class implements IEnumerable, ICollection, and IList interfaces. So, you can create an object of ArrayList class and assign it to the variable of any base interface type. However, if you assign it to IEnumerable or ICollection type variable then you won't be able to add elements and access ArrayList by index.

For Ex:

     class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();//can add elements with additional methods
            IList _ArrayIList = new ArrayList();//can add elements
            ICollection _ArrayICollection = new ArrayList();//can not add elements
            IEnumerable _ArrayIEnumerable = new ArrayList();//can not add elements

      
        }
    }

From above example you can see that using ArrayList is more useful compare to others.because ArrayList class contains some additional methods which are not the members of IList interface such as AddRange(), BinarySearch(), Repeat(), Reverse(), etc.

Properties of ArrayList

  1. Capicity: Gets or sets the number of elements that the ArrayList can contain
  2. Count:Gets the number of elements actually contained in the ArrayList.
  3. IsFixedSize: Gets a value indicating whether the ArrayList has a fixed size.
  4. IsReadOnly: Gets a value indicating whether the ArrayList is read-only.
  5. Item:Gets or sets the element at the specified index.

Methods Of ArrayList

1.Add()/AddRange: Add() method adds single elements at the end of ArrayList.
AddRange() method adds all the elements from the specified collection into ArrayList

 Example:

class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();
            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);

            _ArrayList2.AddRange(_ArrayList);//Adding entire collection

            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }
    }
                                                                                                                                                            




2.Insert()/InsertRange():

Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList.       

Example:   

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.Insert(1, "Inserted"); // Inserted Single item at particular index

            _ArrayList2.AddRange(_ArrayList);
            _ArrayList2.InsertRange(3,_ArrayList); //Insert entire list from the particular index.

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            foreach (var i in _ArrayList2)
            {
                Console.WriteLine("Items in ArrayList - 2 {0}", i);
            }
            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }
    }
    
                                                                                                                                                            

3.Remove()/Remove Range():
Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.

  static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.Remove(1); //Remove 1 from Arraylist


            _ArrayList2.AddRange(_ArrayList);
            _ArrayList2.Add("New Values");
            _ArrayList2.RemoveRange(0,3);//Remove 3 element starting from 0th.
          

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            foreach (var i in _ArrayList2)
            {
                Console.WriteLine("Items in ArrayList - 2 {0}", i);
            }
            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }

                                                                                                                                                        


4.RemoveAt():

Removes the element at the specified index from the ArrayList.

Example  

static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.RemoveAt(2); //Remove 2 index element from Arraylist

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
 
            Console.ReadLine();

        }
                                                                                                                                                         

5.Sort & Reverse():

The ArrayList class includes Sort() and Reverse() method. The Sort() method arranges elements in ascending order. However, all the elements should have same data type so that it can compare with default comparer otherwise it will throw runtime exception.

The Reverse() method arranges elements in reverse order. Last element at zero index and so on.

Example:

   static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
         

            _ArrayList.Add(1);
            _ArrayList.Add(2);
            _ArrayList.Add(2);
            _ArrayList.Add(3);
            
            _ArrayList.Sort(); // Sorting
            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            _ArrayList.Reverse(); //Reverse
            foreach (var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            Console.ReadLine();

        }                                                                                                                                                            


6.Contains

The Contains() method checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.

Example:

 static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add(2);
            _ArrayList.Add(2);
            _ArrayList.Add(3);
         
            _ArrayList.Sort();
            Console.WriteLine(_ArrayList.Contains(3)); //Print true
            Console.ReadLine();

        }


Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...