Breaking News
yeni film izle hd film seyret film izle

Collections and Collection classes in C#

Arrays are useful, but there are some limitations of using arrays in our applications because arrays are of fixed size. Once we have created an array, it will not automatically resize if we try to add more items in the list after the given size of the array. To resolve this problem of resizing an array, .Net provides you a solution of this problem in the form of collections. Collections are better optimized to handle resizing an array.
 
Collections are the fundamental part of programming in Visual C#. You may not have noticed but every windows form maintains a collection of all the controls on it using the controls property which is of the type ControlCollection. ControlCollection is a collection class defined in System.Windows.Forms.Control namespace.
 
It is used specially to create collections of objects of Control class or classes derived from it. You can see that any control added to the form gets added to the Controls collection. If you want to add a control to your form through code, you add that control to the Controls collection yourself.
 
Collection Classes
 
.Net Framework provides you a number of collection classes. Some of the most useful collection classes are defined in the System.Collections namespace and they are as follows:
 
? ArrayList
? BitArray
? HashTable
? SortedList
? Queue
? Stack
 
ArrayList
 
An ArrayList is an array that can dynamically grow and shrink.
 
Properties
 
• Capacity – Gets or sets the number of elements that the ArrayList can contain.

• Count – Gets the number of elements contained in an ArrayList object.

• IsFixedSize – Gets a value indicating whether a ArrayList object has a fixed size. A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but does allow the modification of existing elements.

• IsReadOnly – It obtains a value indicating whether the ArrayList is read-only.

• Item – Gets or sets the element at the specified index.

 
Methods
 
• Add (value) – Adds an object to the end of the ArrayList.

• AddRange – It adds the elements of an ICollection to the end of the ArrayList.

• BinarySearch – It uses a binary search algorithm to locate a specific element in the sorted ArrayList or a portion of it.

• Clear – It removes all elements from ArrayList.

• Contains – It determines whether an element is in the ArrayList.

• GetRange – It returns an ArrayList which represents a subset of the elements in the source ArrayList.

• IndexOf – It returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.

• Insert – It inserts an element into the ArrayList at the specified index.

• InsertRange – It inserts the elements of a collection into the ArrayList at the specified index.

• LastIndexOf – It returns the zero-based index of the last occurrence of a value in the ArrayList or in a portion of it.

• Remove – It removes the first occurrence of a specified object from the ArrayList.

• RemoveAt – It removes the element at the specified index of the ArrayList.

• RemoveRange – It removes a range of elements from the ArrayList.

• Repeat – It returns an ArrayList whose elements are copied of the specified value.

• Reverse – It reverses the order of the elements in the ArrayList or a portion of it.

• SetRange – It copies the elements of a collection over a range of the elements in the ArrayList.

• Sort – It sorts the elements in the ArrayList or a portion of it.

• ToArray – It copies the elements of the ArrayList to a new array.

 
Using an ArrayList to store numbers
 
For example, here is our earlier read loop revised to add elements to the container:
 
/*Illustrates the use of the SortedList methods*/
using System.Collections;
private void readFile()
{
	//Create a new ArrayList
	ArrayList m_text = new ArrayList();
	string  text_line;

	while (( text_line = m_reader.ReadLine() ) != null )
	{
		if ( text_line.Length == 0 )
			continue;

		// insert the line at the back of the container
		m_text.Add( text_line );
	}
	// let's see how many we actually added...
	Console.WriteLine( "We inserted {0} lines", text.Count );
}
 
The simplest and most efficient way to insert a single element is to use the Add () function. It inserts the new element at the back of the list:
 
text.Add( text_line );
 
Count returns the number of elements held in the ArrayList object:
 
Console.WriteLine( “We inserted {0} lines”, text.Count );
 
Just as we do for all reference types, we create an ArrayList object on the managed heap using the new expression:
 
ArrayList text = new ArrayList();
 
The elements of an ArrayList are stored in a portion of closest memory. When that memory becomes full, a larger portion of closest memory has to be allocated (usually twice the size) and the existing elements are copied into this new portion. We call this portion is the capacity of the ArrayList object.
 
The capacity of an ArrayList represents the total number of elements that can be added before a new memory portion needs to be allocated. The count of an ArrayList represents the number of elements currently stored within the ArrayList object. By default, an empty ArrayList object begins life with a capacity of 16 elements.
 
To override the default capacity, we pass in an alternative capacity when we create the ArrayList object—
 
for example..
 
Where, newCapacity represents a logical integer value. Capacity returns the current capacity of the ArrayList object:
 
Console.WriteLine(“Count {0} Capacity {1}”,text.Count, text.Capacity);
 
Once we’ve completed our element insertion, we can trim the capacity of the ArrayList to the actual element count using the TrimToSize () method:
 
text.TrimToSize();
 
Trimming an ArrayList object does not restrict our ability to insert additional elements. If we do, however, we once again increase the capacity.
 
BitArray
 
BitArray manage an array of the binary representation of the values that you put in them, with true for 1 and false for 0.
 
Properties
 
? Count – It obtains the number of elements contained in the BitArray.
? Item – It obtains the value of the bit at a specific position in the BitArray.
? Length – It obtains or sets the number of elements in the BitArray.
 
Methods
 
And – It performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specific BitArray.

CopyTo – It copies the entire BitArray to a compatible one-dimensional array, starting at the specified index of the target array.

Get – It gets the value of the bit at a specified position in the BitArray.

Not – It inverts all the bit values in the current BitArray so that elements set to true are changed to false, and elements set to false are changed to true.

Or – It performs the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

Set – It sets the bit at a specified position in the BitArray to the specified value.

SetAll – It set all bits in the BitArray to the specified value.

Xor – It performs the bitwise exclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

 
Example
 
Creating BitArrays
 
BitArray myBitArray = new BitArray( 5 );
Creates a BitArray of length 5 with all values set to false.
 
BitArray myBitArray = new BitArray( 5, false );
Creates a BitArray of length 5 with all values set to false.
 
BitArray myBitArray = new BitArray( 5, true );
Creates a BitArray of length 5 with all values set to true.
 
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };

BitArray myBitArray = new BitArray( myBytes );

Note: Creates a BitArray of length 40 with bit 
pattern equal to the binary equivalent of 
each number in the byte array (8 bits per byte). 

bool[] myBools = new bool[5] { true, false, true, true, false };

BitArray myBitArray = new BitArray( myBools );

Creates a BitArray of length 5 with bit pattern, equal to the bool array.
 
int[]  myInts  = new int[5] { 6, 7, 8, 9, 10 };

BitArray myBitArray = new BitArray( myInts );
 
Note: Creates a BitArray of length 160 with bit pattern equal to the binary equivalent of each number in the int array (32 bits per int).
 
Set Value – Convert value to BitArray
 
Most of the time when you are using the BitArray class, you simply want to set a value. On initialization this can be done as .
 
byte[] value = {0x11};
BitArray myBits = new BitArray(value);
 
But how can the value are changed later in the code? Unfortunately no method exists in the BitArray class to do this. Therefore you must implement your own method such as the following:
 
BitArray myBits = new BitArray(8); //define the size
 
//setting a value
for (byte x = 0; x < myBits.Count; x++)
{
  myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
}
 
This type of code can be done in many complicated ways. The use of a shift operation, bit mask operation and short hand‘if statement’simplify this into just 2 easily understandable lines of code.
 
Get Value – Convert BitArray to value
 
Another missing feature of the BitArray class is to get the value of the array.
 
byte value = 0x00;
 
for (byte x = 0; x < bArray.Count; x++)
{
  value |= (byte) ((bArray[x] == true) ? (0x01 << x): 0x00);
}
 
To Download Array List example Click here.
 
HashTable
 
The HashTable class represents a collection of key/value pairs that are organized based on the hash code of the key. Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be a null reference, but a value can be.
 
Properties
 
Count – It obtains the number of key/value pairs contained in the HashTable.
Item – It obtains the value associated with the specified key.
Keys – It obtains an ICollection containing the keys in the HashTable.
Values – It obtains an ICollection containing the values in the HashTable.
 
Method
 
Add – It adds an element with the specified key and values into the HashTable.

Clear – It removes all elements from the HashTable.

ContainsKey – It determines whether the HashTable contains a specific key.

ContainsValue – It determines whether the HashTable contains a specific value.

CopyTo – It copies the HashTable elements to a one-dimensional array instance at the specified index.

Remove – It removes the element with the specified key from the HashTable.

 
Example
 
Adding Elements to the Table
 
// Add some elements to the hash table. 
There are no duplicate keys, //but some of the values are duplicates.
exampleTable.Add( "txt", "notepad.exe" );
exampleTable.Add( "bmp", "paint.exe" );
exampleTable.Add( "dib", "paint.exe" );
exampleTable.Add( "rtf", "wordpad.exe" );
 
Using the Default Item Property to Change Its Corresponding Key
 
// The default Item property can be used to change the value associated //with a key.
exampleTable[ "rtf" ] = "winword.exe";
 
// If a key does not exist, setting the default Item property
// for that key adds a new key/value pair.
exampleTable[ "doc" ] = "winword.exe";
 
//ContainsKey can be used to test keys before inserting them.
if( !exampleTable.ContainsKey( "ht" ) )
{
  exampleTable.Add( "ht", "hypertrm.exe" );
}
 
Using The Remove Method To Delete A Value Or Key From The Table
 
// Use the Remove method to remove a key/value pair.
exampleTable.Remove( “doc” );
 
SortedList
 
The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index. A SortedList is a mixture of a HashTable and an Array. When an element is accessed by its key using the Item indexer property, it behaves like a HashTable. When an element is accessed by its index using GetByIndex or SetByIndex, it behaves like an Array.
 
Properties
 
• Capacity – Gets or sets the capacity of a SortedList object.

• Count – Gets the number of elements contained in a SortedList object.

• IsFixedSize – Gets a value indicating whether a SortedList object has a fixed size. A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but does allow the modification of existing elements.

• Item – Gets and sets the value associated with a specific key in a SortedList object.

• Keys – Gets the keys in a SortedList object.

• Values – Gets the values in a SortedList object.

 
Method
 
Add – It adds an element with the specified key and value to the SortedList.

Clear – It removes all elements from the SortedList.

Clone – It copies only the elements of the collection, whether they are reference types or value types, but does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.

ContainsKey – It determines whether the SortedList contains the specific key.

ContainsValue – It determines whether the SortedList contains the specific value.

GetByIndex – It gets the value at the specified index of the SortedList.

GetKey – It gets the key at the specified index of the SortedList.

GetKeyList – It gets the key in the SortedList.

GetValueList – It gets the value in the SortedList.

IndexOfKey – It returns the zero-based index of the specified key in the SortedList.

IndexOfValue – It returns the zero-based index of the first occurrence of the specified value in the SortedList.

Remove – It removes the element with the specified key from SortedList.

RemoveAt – It removes the element at the specified index of SortedList.

SetByIndex – It replaces the value at a specified index in the SortedList.

 
Example
 
/*Illustrates the use of the SortedList methods*/
using System;
using System.Collections;

public class ExampleSortedList
{
  public static void Main()
  {
    // create a SortedList object
    SortedList mySortedList = new SortedList();

    // add elements containing US state abbreviations and state
    // names to mySortedList using the Add() method
    mySortedList.Add("NY", "New York");
    mySortedList.Add("FL", "Florida");
    mySortedList.Add("AL", "Alabama");
    mySortedList.Add("WY", "Wyoming");
    mySortedList.Add("CA", "California");

    // display the keys for mySortedList using the Keys property
    foreach (string myKey in mySortedList.Keys)
    {
      Console.WriteLine("myKey = " + myKey);
    }

    // display the values for mySortedList using the Values property
    foreach(string myValue in mySortedList.Values)
    {
      Console.WriteLine("myValue = " + myValue);
    }

    // use the ContainsKey() method to check if mySortedList
    // contains the key "FL"
    if (mySortedList.ContainsKey("FL"))
    {
      Console.WriteLine("mySortedList contains the key FL");
    }

    // use the ContainsValue() method to check if mySortedList
    // contains the value "Florida"
    if (mySortedList.ContainsValue("Florida"))
    {
      Console.WriteLine("mySortedList contains the value Florida");
    }

    // use the Remove() method to remove FL from mySortedList
    Console.WriteLine("Removing FL from mySortedList");
    mySortedList.Remove("FL");

    // get the key at index 3 using the GetKey() method
    string keyAtIndex3 = (string) mySortedList.GetKey(3);
    Console.WriteLine("The key at index 3 is " + keyAtIndex3);

    // get the index of the element with the key "NY"
    // using the IndexOfKey() method
    int myIndex = mySortedList.IndexOfKey("NY");
    Console.WriteLine("The index of NY is " + myIndex);

    // get the index of the element with the value "New York"
    // using the IndexOfValue() method
    myIndex = mySortedList.IndexOfValue("New York");
    Console.WriteLine("The index of New York is " + myIndex);

    //replace the value of the element at myIndex with "New York State"
    // using the SetByIndex() method
    Console.WriteLine("Replacing the value New York with New York State");
    mySortedList.SetByIndex(myIndex, "New York State");

    // get the key list using the GetKeyList() method
    Console.WriteLine("Getting the key list");
    IList myKeyList = mySortedList.GetKeyList();
    foreach(string myKey in myKeyList)
    {
      Console.WriteLine("myKey = " + myKey);
    }

    // get the value list using the GetValueList() method
    Console.WriteLine("Getting the value list");
    IList myValueList = mySortedList.GetValueList();
    foreach(string myValue in myValueList)
    {
      Console.WriteLine("myValue = " + myValue);
    }
  }
}
 
To Download Hash Table example Click here.
 
Queue
 
The Queue class represents a way of managing elements in a collection using the First in First out (FIFO) technique for adding and removing elements.FIFO simply means that whichever element was added first in the collection list that element will automatically removed first.
 
FIFO (First In First Out) In the Queue Class
 
Elements are added to the end of the collection and removed from the beginning. In this way the element that was added first will be the one removed or retrieved first.
 
Properties
 
Count – It gets the number of elements contained in the Queue.

IsSynchronized – It gets a value indicating whether access to the Queue is synchronized.

SyncRoot – It gets an object that can be used to synchronize access to the Queue.

 
Methods
 
Clear – It removes all objects from the Queue.

Clone – Creates a shallow copy of the Queue.

Contains – Determines whether an element is in the Queue.

CopyTo – Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.

Dequeue – Removes and returns the object at the beginning of the Queue.

Enqueue – Adds an object to the end of the Queue.

GetType – Gets the Type of the current instance.

Peek – Returns the object at the beginning of the Queue without removing it.

ToArray – Copies the Queue elements to a new array.

ToString – Returns a String that represents the current Object.

TrimToSize – Sets the capacity to the actual number of elements in the Queue.

 
Example
 
Create and Populate a Queue
 
// Create a queue
Queue multiplesOfFive = new Queue();
 
// populate the array with the first 10 multiples of 5
for (int i = 0 ; i < 10 ; i++) {
  multiplesOfFive.Enqueue( i * 5 );
}
 
Remove Elements From the Queue
 
// Create the queue
Queue primes = new Queue();
 
primes.Enqueue( 2 );
primes.Enqueue( 3 );
primes.Enqueue( 5 );
primes.Enqueue( 7 );
 
// Dequeue will return the first item that was added and remove //it
 
// firstPrime will be 2
int firstPrime = (int) primes.Dequeue();
 
// secondPrime will be 3
int secondPrime = (int) primes.Dequeue();
 
View First Element Without Removing It
 
// Create the queue
Queue messages = new Queue();
 
messages.Enqueue( "Joe:Hey Joe..." );
messages.Enqueue( "Bob:I'll see you tommorrow" );
messages.Enqueue( "Jane:Yesterday, I was gone..." );
messages.Enqueue( "Karen:How are you?" );
 
//Peek will allow a the first item to be read without removing //it
string firstMessage = (string) messages.Peek();
 
if( firstMessage.StartsWith( "Bob" ) ){
   
  messages.Dequeue();
 
  // Display message
  // ...
}
 
To Download Queue Collection example Click here.
 
Stack
 
The Stack class represents a way of managing elements in a collection using the Last in First out (LIFO) technique for adding and removing elements. LIFO simply means that the which element was last added to the collection list that element will automatically removed at the first.
 
LIFO in a Stack
 
In the Stack class elements are added to the end of a collection and removed from the end as well. In this way the last element added to the stack will also be the first one removed or retrieved.
 
Properties
 
Count – Gets the number of elements contained in the Stack.

IsSynchronized – Gets a value indicating whether access to the Stack is synchronized (thread safe).

SyncRoot – Gets an object that can be used to synchronize access to the Stack.

 
Methods
 
Clear – Removes all objects from the Stack.

Clone – Creates a shallow copy of the Stack.
Contains – Determines whether an element is in the Stack.

CopyTo – Copies the Stack to an existing one-dimensional Array, starting at the specified array index.

GetEnumerator – Returns an IEnumerator for the Stack.

GetType – Gets the Type of the current instance.

Peek – Returns the object at the top of the Stack without removing it.

Pop – Removes and returns the object at the top of the Stack.

Push – Inserts an object at the top of the Stack.

ToArray – Copies the Stack to a new array.

ToString – Returns a String that represents the current Object.

 
Example
 
using System;
using System.Collections;
public class SamplesStack  
{
   public static void Main()  
   {
      // Creates and initializes a new Stack.
      Stack myStack = new Stack();
      myStack.Push("Hello");
      myStack.Push("World");
      myStack.Push("!");

      // Displays the properties and values of the Stack.
      Console.WriteLine( "myStack" );
      Console.WriteLine( "\tCount:    {0}", myStack.Count );
      Console.Write( "\tValues:" );
      PrintValues( myStack );
   }

   public static void PrintValues( IEnumerable myCollection )  
   {
      foreach ( Object obj in myCollection )
         Console.Write( "    {0}", obj );
      Console.WriteLine();
   }
}
 
To Download Stack Collection example Click here.
 
Practical Example (ShortedList):
 
testSortedList.cs
 
using System;
using System.Collections;
using System.Text;

namespace testSortedList
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a SortedList object
            SortedList mySortedList = new SortedList();

            // add elements containing US state abbreviations and state
            // names to mySortedList using the Add() method
            mySortedList.Add("NY", "New York");
            mySortedList.Add("FL", "Florida");
            mySortedList.Add("AL", "Alabama");
            mySortedList.Add("WY", "Wyoming");
            mySortedList.Add("CA", "California");

            // display the keys for mySortedList using the Keys property
            foreach (string myKey in mySortedList.Keys)
            {
                Console.WriteLine("myKey = " + myKey);
            }

            // display the values for mySortedList using the Values property
            foreach (string myValue in mySortedList.Values)
            {
                Console.WriteLine("myValue = " + myValue);
            }

            // use the ContainsKey() method to check if mySortedList
            // contains the key "FL"
            if (mySortedList.ContainsKey("FL"))
            {
                Console.WriteLine("mySortedList contains the key FL");
            }

            // use the ContainsValue() method to check if mySortedList
            // contains the value "Florida"
            if (mySortedList.ContainsValue("Florida"))
            {
                Console.WriteLine("mySortedList contains the value Florida");
            }

            // use the Remove() method to remove FL from mySortedList
            Console.WriteLine("Removing FL from mySortedList");
            mySortedList.Remove("FL");

            // get the key at index 3 using the GetKey() method
            string keyAtIndex3 = (string)mySortedList.GetKey(3);
            Console.WriteLine("The key at index 3 is " + keyAtIndex3);

            // get the index of the element with the key "NY"
            // using the IndexOfKey() method
            int myIndex = mySortedList.IndexOfKey("NY");
            Console.WriteLine("The index of NY is " + myIndex);

            // get the index of the element with the value "New York"
            // using the IndexOfValue() method
            myIndex = mySortedList.IndexOfValue("New York");
            Console.WriteLine("The index of New York is " + myIndex);

            //replace the value of the element at myIndex with "New York State"
            // using the SetByIndex() method
            Console.WriteLine("Replacing the value New York with New York State");
            mySortedList.SetByIndex(myIndex, "New York State");

            // get the key list using the GetKeyList() method
            Console.WriteLine("Getting the key list");
            IList myKeyList = mySortedList.GetKeyList();
            foreach (string myKey in myKeyList)
            {
                Console.WriteLine("myKey = " + myKey);
            }

            // get the value list using the GetValueList() method
            Console.WriteLine("Getting the value list");
            IList myValueList = mySortedList.GetValueList();
            foreach (string myValue in myValueList)
            {
                Console.WriteLine("myValue = " + myValue);
            }
            Console.ReadLine();
        }
    }
}

 
The Output is:
 
img
 
To Download Sorted List example Click here.
 
To view downloaded examples, Please Ensure that .NET Framework is installed on your system..
 

Check Also

Exceptions In C#

System.Exception is the base class for all other exceptions. Below this level are the System.ApplicationException …