Sunday, March 9, 2014

Collections


Collection

  • The concept of collections is basically developed from Arrays.
  • Already you know that, arrays are multiple value containers of fixed type.
  • In order to hold different types of values on the same array, you require collections.
  • Another advantage of collections is those are dynamic sizable. In other words, the array is of fixed size and the collection is of dynamic size.
  • Finally, if you don‘t know how many values are to be stored in the array at the time of its declaration,  you  require  to  use  collections;  (or)  if  you  want  to  store  different  type  of values in the same array, at that case also, you require to use collections.
  • .NET offers some pre-defined classes for maintenance of collections.
Collection Classes:

List:

  1. Contains n no. of values of same type. It‘s a generic class.
  2. This is member of ―System.Collections.Generic” namespace.

ArrayList:

  1. Contains n no. of values of different types.
  2. This is member of System.Collections namespace
Implementation of “List” class:
  • Import namespace:
          using System.Collections.Generic;
  • Create instance:
         List<data type> obj = new List<data type>();
  • Add values:
         obj.Add(value);
  • Get the currently existing no. of values in the collection:
         obj.Count
  • Get the individual element in the collection:
Implementation of “ArrayList” class:
  • Import namespace:
          using System.Collections;
  • Create instance:
          ArrayList obj = new ArayList();
  • Add values:
          obj.Add(value);
  • Get the currently existing no. of values in the collection:
          obj.Count
  • Get the individual element in the collection:
          obj[index];
Program of List Class
using System.Collections.Generic;
namespace ListClass
{
class Program
 {
  static void Main(string[] args)
  {
   List MyMessages = new List();
   MyMessages.Add("Good Morning");
   MyMessages.Add("Good Afternoon");
   MyMessages.Add("Good Evening");
   MyMessages.Add("Good Night");
 //MyMessages.Add(10); //error
   Console.WriteLine(MyMessages.Count + " messages found.\n");
   foreach (string s in MyMessages)
   {
    Console.WriteLine(s);
   }
   Console.Read();
  }
 }
}
PROGRAM OF ARRAYLIST CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ArrayListClass
{
class Program
 {
  static void Main(string[] args)
  {
   ArrayList al = new ArrayList();
   al.Add("Hai");
   al.Add("How r u");
   al.Add(1000);
   al.Add(true);
   al.Add(DateTime.Now);
   Console.WriteLine(al.Count + " values found.\n");
  for (int i = 0; i < al.Count; i++)
   Console.WriteLine(al[i]);
   Console.Read();
  }
 }
}