Sunday, July 26, 2009

Collections in C# 2 Part 1

Collections is introduced in C# 2 . To make the strongly typed collections

C#1 : it contains array list not collections class

Disadvantage of Arraylist
  • arraylist has no compile time information.If any mismatch type is there error will throw at runtime only.(It is weekly typed collection)
E.g :public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
}
public class program
{
public static void Main()
{
ArrayList al = new ArrayList();
al.Add(new Employee("Anish", 20000m));
al.Add(new Employee("marokey",30000m));

foreach (Employee emp in al)
{
Console.Write(emp.Name);
Console.Write(emp.Salary);
Console.WriteLine();
}
}
}
Result : Anish20000
marokey30000

Just look the below code produce no error at compile time but throws error at runtime
public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
}
public class program
{
public static void Main()
{
ArrayList al = new ArrayList();
al.Add(new Employee("Anish", 2000m));
al.Add(new Employee("marokey",30000m));
al.Add("Error");

foreach (Employee emp in al)
{
Console.Write(emp.Name);
Console.Write(emp.Salary);
Console.WriteLine();
}
}
}

Error : Unable to cast object of type 'System.String' to type 'dummy.Employee

Array list allows all items .It doesnot consider about the item

To avoid these types of error collection class is introduced .

public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}

public Employee(string name)
{
this.name = name;
}
}
public class program
{
public static void Main()
{
List empList = new List();
empList.Add(new Employee("Anish", 2000m));
empList.Add(new Employee("marokey", 30000m));
empList.Add("Error");
}
}

During compile time itself it throws error
Error 1 :The best overloaded method match for 'System.Collections.Generic.List.Add(dummy.Employee)' has some invalid arguments
Error 2 : cannot convert from 'string' to 'dummy.Employee'

Note : This is known as strongly typed collections


Collection Class

1)ArrayList : A simple resizeable ,indexbased collection of objects
2)SortedList : A sorted Collection of name/value pairs.And accessible by key and by index

E.g : static void Main()
{
SortedList sl = new SortedList();
sl.Add("maorkey",0);
sl.Add("Anish",1);

Console.WriteLine( sl.GetKey(1));
}

Note :When it creates a list it automatically sort the data based on the object key.
It wont allow redundant values.

E.g: static void Main()
{
SortedList sl = new SortedList();
sl.Add("Anish",0);
sl.Add("Anish",1);

Console.WriteLine( sl.GetKey(1));
}

//Error (Item is has already been added)

3)Queue : Represent the first-in-first-out collection of objects

static void Main()
{
Queue myQ = new Queue();
myQ.Enqueue("a");
myQ.Enqueue("n");
myQ.Enqueue("i");

Console.WriteLine(myQ.Dequeue());
Console.WriteLine(myQ.Dequeue());
Console.WriteLine(myQ.Dequeue());
}

Result : ani (FIFO manner)


Better way of using Queue is generic Queue

E.g : static void Main()
{
Queue smyQ = new Queue();
smyQ.Enqueue("a");
smyQ.Enqueue("n");
smyQ.Enqueue("i");

Console.WriteLine(smyQ.Dequeue());
Console.WriteLine(smyQ.Dequeue());
}

Note : This queue allows only sting to iterate.
4)Stack : Last in First out non generic collection of objects

static void Main()
{
Stack sTack = new Stack();
sTack.Push("a");
sTack.Push("n");
sTack.Push("i");

Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
}

Result : ina(LIFO manner)

Generic Stack is the better way of using

static void Main()
{
Stack sTack = new Stack();
sTack.Push("a");
sTack.Push("n");
sTack.Push("i");

Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
}

5)HashTable : A collection of name/value pair of objects that allow retrieval of name or index

E.g: static void Main()
{
Hashtable openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");


Console.WriteLine();
foreach (DictionaryEntry de in openWith)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
}

Generic HashTable is not there .Because it takes Object as value and key.Dictionary class can act as generic hashTable not Exactly.Because there we can set the object key and value.

6)BitArray :compact array of bit values ,Which as represent as Boolean.

static void Main()
{


BitArray myBA1 = new BitArray(5);
Console.WriteLine("myBA1");
Console.WriteLine(" Count: {0}", myBA1.Count);
Console.WriteLine(" Length: {0}", myBA1.Length);
Console.WriteLine(" Values:");
PrintValues(myBA1, 8);
}

public static void PrintValues(IEnumerable myList, int myWidth)
{
int i = myWidth;
foreach (Object obj in myList)
{
if (i <= 0)
{
i = myWidth;
Console.WriteLine();
}
i--;
Console.Write("{0,8}", obj);
}
Console.WriteLine();
}
}

7)Stirng Collection : It allows null and duplicate values


static void Main()
{


StringCollection myCol = new StringCollection();

// Add a range of elements from an array to the end of the StringCollection.
String[] myArr = new String[] { "RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED" };
myCol.AddRange(myArr);
PrintValues1(myCol);
}


public static void PrintValues1(StringCollection myCol)
{
foreach (Object obj in myCol)
Console.WriteLine(" {0}", obj);
Console.WriteLine();
}

8) StringDictionary :collection of name/value pair .It can retrieve by name or index.It is strongly typed .


static void Main()
{


StringDictionary myCol = new StringDictionary();

// Add a range of elements from an array to the end of the StringCollection.
myCol.Add("red", "0");
myCol.Add("blue", "1");
myCol.Add("green", "2");
PrintKeysAndValues1(myCol);
}


public static void PrintKeysAndValues1(StringDictionary myCol)
{
Console.WriteLine(" KEY VALUE");
foreach (DictionaryEntry de in myCol)
Console.WriteLine(" {0,-25} {1}", de.Key, de.Value);
Console.WriteLine();
}
9) List directory :An efficient collection to store small list of objects .
It is smaller and faster than the HashTable .If the number of element is 10 or less.

10)HybridDictionary :Using a ListDictionary while collection is small and it switches to HashTable when he collection is large.

11)NameValueCollection :Collection of name/ value pairs . It is less performance than HashTable.


0 comments:

 
Counter