In this article we will deal with C# collections
and Generic Collection with example. Besides of these we also can know about
its benefits and limitations.
A
collection can be defined as a group of related items that can be referred to
as a single unit. For data storage and retrieval .NET
framework provides a special classes for different types of collection,
such as ArrayList, Hashtable, queues, Dictionaries etc.
There are two types of collection are
available in C#. They are Standard
Collection and another is Generic
Collection.
Standard Collection
It comes under the System.Collections
namespace which provides you with many classes and interfaces. Some of them
are - ArrayList, List, Stack, ICollection, IEnumerable,
IDictionary etc.
Following are some frequently
used classes in System.collection
namespace :
Class
|
Description
|
ArrayList
|
ArrayList represents an array of
objects whose size is dynamically increased as required.It provides type
safety and in some cases provides better performance, especially when sorting
value types.
|
Hashtable
|
It represents a collection of
key/value pairs that are organized based on the hash code of the key. A key
can be of any data type but should not be null.
|
Queue
|
Represents a first in, first out
(FIFO) collection of objects. the capacity of queue is number of elements the
queue can hold. it accepts null reference as a valid value and allows
duplicate.
|
Stack
|
Represents a last in, first out (LIFO)
collection of objects. it accepts null reference as a valid value and allows
duplicate.
|
ArrayList
: An
ArrayList is a collection from System.collection.It is a dynamic array whose
size can increase or decrease dynamically. It can hold the items of different types.
Elements of the ArrayList can be accessed using integer index randomly. And the
indexes in this collection are zero-based. An arraylist supports multiple
readers concurrently. ArrayList is loosely typed collection and it never ensure
compile-Time type checking.
Benefits
of ArrayLists
- Array List starts with Zero elements, its capacity increase/decrease automatically when we add or delete the elements from the ArrayList.
- We do not need to specify the array size. By default its capacity is Zero. And to retrieve its data we use the index number.
- We can remove any element from an Arraylist very easily.
Limitations
of ArrayLists
- The flexibility of ArrayList comes at a cost of performance. Since memory allocation is a very expensive business, the fixed number of elements of the simple array makes it much faster to work with.
Example
:
ArrayList objArray = new ArrayList();
Once you create an instance of the ArrayList object. You don't need to specify the size. It creates empty ArrayList object, you can use the Add() method to add elements to it, as in:
Once you create an instance of the ArrayList object. You don't need to specify the size. It creates empty ArrayList object, you can use the Add() method to add elements to it, as in:
static void
main()
{
ArrarList lstArr=new ArrayList();
lstArr.Add("Bhimsen");
lstArr.Add("112");
lstArr.Add(new
Empty());
lstArr.Remove("112")
foreach(object
item in lstArr)
{
Console.WriteLine(item);
}
}
}
Hashtable
Limitations of Hashtable
All the key in the hastable should be unique. Becouse it works as an index.
Since, hashtable requires boxing and unboxing, due to that it is slower than the generic collection's objects.
Example
The following Hashtable program uses a date index. First we define a Hashtable object and add some predefined dates. Thereafter we create a DateTime type variable to store user input and finally we display the output.
using System;
using System.Collections;
namespace CollectionApp {
class Program
{
static void Main(string[] args)
{
Hashtable obj = new Hashtable();
//Adding elements in hastable's object.
obj[Convert.ToInt32("2")] = 222;
obj["Two"] = "Bhimsen";
//display data
Console.WriteLine(obj[2]);
Console.WriteLine(obj["Two"]);
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
}
}
Hashtable is a data structure that implements the IDictionary interface. It stores each element in the form of key/Value. A key cannot be null but value can be null. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.
Queue
Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.
Example
using System;
using System.Collections.Generic;
public class QueueExample
{
static void Main()
{
Queue<string> strQueue = new Queue<string>();
strQueue.Enqueue("Bhimsen");
strQueue.Enqueue("Avnish");
strQueue.Enqueue("Shakti");
Console.WriteLine(strQueue.Dequeue());
Console.WriteLine(strQueue.Peek());
Console.WriteLine(strQueue.Peek());
Console.WriteLine();
foreach(string name in strQueue)
{
Console.WriteLine(name);
}
}
}
Stack
Stack is a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, insertion of elements is known as push operation and deletion of element are known as pop operation. The capacity of stack is the number of element the stack can hold. During insertion and deletion of element its capacity increases and decreases respectively.
Example:
using System;
using System.Collections.Generic;
public class StackEx
{
static void Main()
{
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Peek());
Console.WriteLine(stack.Peek());
Console.WriteLine();
foreach(int item in stack)
{
Console.WriteLine(item);
}
}
}
A hashtable can hold numbers of element. Its default capacity is zero. When element are added to hashtable, its capacity automatically increased as required.The key of hashtable may be any types such as string, int, datatime etc.To find the data in hashtable we uses the key, and it gives the correspondent value. And we also can remove its element easily using the key.
Benefits of Hashtable
- A hashtable can hold numbers of element. Its default capacity is zero. When element are added to hashtable, its capacity automatically increased as required.
- The key of hashtable may be any types such as string, int, datatime etc.
- To find the data in hashtable we uses the key, and it gives the correspondent value. And we also can remove its element easily using the key.
Limitations of Hashtable
All the key in the hastable should be unique. Becouse it works as an index.
Since, hashtable requires boxing and unboxing, due to that it is slower than the generic collection's objects.
Example
The following Hashtable program uses a date index. First we define a Hashtable object and add some predefined dates. Thereafter we create a DateTime type variable to store user input and finally we display the output.
using System;
using System.Collections;
namespace CollectionApp {
class Program
{
static void Main(string[] args)
{
Hashtable obj = new Hashtable();
//Adding elements in hastable's object.
obj[Convert.ToInt32("2")] = 222;
obj["Two"] = "Bhimsen";
//display data
Console.WriteLine(obj[2]);
Console.WriteLine(obj["Two"]);
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
}
}
Hashtable is a data structure that implements the IDictionary interface. It stores each element in the form of key/Value. A key cannot be null but value can be null. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.
Queue
Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.
Example
using System;
using System.Collections.Generic;
public class QueueExample
{
static void Main()
{
Queue<string> strQueue = new Queue<string>();
strQueue.Enqueue("Bhimsen");
strQueue.Enqueue("Avnish");
strQueue.Enqueue("Shakti");
Console.WriteLine(strQueue.Dequeue());
Console.WriteLine(strQueue.Peek());
Console.WriteLine(strQueue.Peek());
Console.WriteLine();
foreach(string name in strQueue)
{
Console.WriteLine(name);
}
}
}
Stack
Stack is a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, insertion of elements is known as push operation and deletion of element are known as pop operation. The capacity of stack is the number of element the stack can hold. During insertion and deletion of element its capacity increases and decreases respectively.
Example:
using System;
using System.Collections.Generic;
public class StackEx
{
static void Main()
{
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Peek());
Console.WriteLine(stack.Peek());
Console.WriteLine();
foreach(int item in stack)
{
Console.WriteLine(item);
}
}
}
Generic Collection
It comes under the System.Collections.Generic
namespace. It is more flexible and provides the type-safety to your class at
compile time. While creating a data structure, you never need to specify the
data type at the time of declaration. It
provides the type safe code with re-usability like as algorithm. In algorithms
such as sorting, searching, comparing etc. you don’t specify what data type(s) the
algorithm operates on. The algorithm can be operates with any types of data. In
the same way Generics operate, you can provide different data type to Generics.
Following are some frequently used classes in System.Collection.Generic namespace
:
Class
|
Description
|
Dictionary<TValue TKey,>
|
It is a generic class which represents
a collection of key/value pairs that are organized based on the key. Each
addition to the dictionary consist of value and its associated key.
Retrieving a value by using its key is very fast.
|
List<T>
|
It is a generic equivalent of the
ArrayList class.It represents a list of objects that can be accessed by
index. it also provides methods to search, sort, and modify lists. Size of
List is increased dynamically as required.
|
Queue<T>
|
Represents a first in, first out
(FIFO) collection of objects.It is useful for storing data in the order they
were received for sequential processing.s
|
SortedList<TValue TKey,>
|
Represents a collection of
key/value pairs that are sorted by key based on the associated IComparer<T>implementation.
|
Stack<T>
|
Represents a last in, first out
(LIFO) collection of objects.
|
Dictionary<TValue TKey,>( Key/Value Pairs)
The Dictionary<TValue TKey,> generic collection enables you to access to elements in a collection by using the key of each element. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is fast because the Dictionary class is implemented as a hash table.
The following example creates a Dictionary collection and iterates through the dictionary by using a For Each statement.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Collection
{
class Program
{
static void Main(string[] args)
{
ReadWriteDictionary();
}
private static void ReadWriteDictionary()
{
Dictionary<string, Student> objStudent = CreateDictionary();
foreach (KeyValuePair<string, Student> kvp in objStudent)
{
Student oStudent = kvp.Value;
Console.WriteLine("key: " + kvp.Key);
Console.WriteLine("values: " + oStudent.Roll + " " +
oStudent.Name + " " + oStudent.Address);
}
Console.ReadLine();
}
private static Dictionary<string, Student> CreateDictionary()
{
var studnets = new Dictionary<string, Student>();
AddDataToDictionary(studnets, "Bhimsen", 10, "New Delhi");
AddDataToDictionary(studnets, "Avnish", 20, "New Delhi");
AddDataToDictionary(studnets, "Shakti", 30, "Noida");
return studnets;
}
private static void AddDataToDictionary(Dictionary<string, Student> lstStudent,
string name, int Roll,string Address)
{
Student objStudent = new Student();
objStudent.Roll = Roll;
objStudent.Name = name;
objStudent.Address = Address;
lstStudent.Add(key: objStudent.Name, value: objStudent);
}
public class Student
{
public string Name { get; set; }
public int Roll { get; set; }
public string Address { get; set; }
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Collection
{
class Program
{
static void Main(string[] args)
{
ReadWriteDictionary();
}
private static void ReadWriteDictionary()
{
Dictionary<string, Student> objStudent = CreateDictionary();
foreach (KeyValuePair<string, Student> kvp in objStudent)
{
Student oStudent = kvp.Value;
Console.WriteLine("key: " + kvp.Key);
Console.WriteLine("values: " + oStudent.Roll + " " +
oStudent.Name + " " + oStudent.Address);
}
Console.ReadLine();
}
private static Dictionary<string, Student> CreateDictionary()
{
var studnets = new Dictionary<string, Student>();
AddDataToDictionary(studnets, "Bhimsen", 10, "New Delhi");
AddDataToDictionary(studnets, "Avnish", 20, "New Delhi");
AddDataToDictionary(studnets, "Shakti", 30, "Noida");
return studnets;
}
private static void AddDataToDictionary(Dictionary<string, Student> lstStudent,
string name, int Roll,string Address)
{
Student objStudent = new Student();
objStudent.Roll = Roll;
objStudent.Name = name;
objStudent.Address = Address;
lstStudent.Add(key: objStudent.Name, value: objStudent);
}
public class Student
{
public string Name { get; set; }
public int Roll { get; set; }
public string Address { get; set; }
}
}
}
List<T>
Represents a list of objects that
can be accessed by index. It also provides methods to search, sort, and modify
lists. Size of List is increased dynamically as required.
List<Student> lstStudents =
new List<Student>();
Student objStudent = new Student();
objStudent.Name = "Rajat";
objStudent.RollNo = 1;
lstStudents.Add(objStudent);
objStudent = new Student();
objStudent.Name = "Sam";
objStudent.RollNo = 2;
lstStudents.Add(objStudent);
foreach (Student currentSt in
lstStudents)
{
Console.WriteLine("Roll #
" + currentSt.RollNo + " " + currentSt.Name);
}
Stake<T>
It
represents a last in, first out (LIFO) collection of objects. The capacity of
stack is the number of elements the stack can hold. The default initial
capacity of stack is 10.
Example:
Stack<int>
stc = new Stack<int>();
A
Stack data structure is created.
stc.Push(1);
stc.Push(4);
The
Push() method adds an item at the top of the stack.
Console.WriteLine(stc.Pop());
The
Pop() method removes and returns the item from the top of the stack.
Console.WriteLine(stc.Peek());
The
Peek() method returns the item from the top of the stack. It does not remove
it.
Queue<T>
Queue
are useful for storing messages in the order they were received for sequential
processing. Objects stored in Queue are inserted at one end and removed from
the other.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Collection
{
class Program
{
static void Main(string[] args)
{
Queue<string> Num = new Queue<string>();
Num.Enqueue("1");
Num.Enqueue("2");
Num.Enqueue("3");
Num.Enqueue("4");
foreach (string number in Num)
{
Console.WriteLine(number);
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Collection
{
class Program
{
static void Main(string[] args)
{
Queue<string> Num = new Queue<string>();
Num.Enqueue("1");
Num.Enqueue("2");
Num.Enqueue("3");
Num.Enqueue("4");
foreach (string number in Num)
{
Console.WriteLine(number);
}
Console.ReadLine();
}
}
}
Hope,
This is helpful to you.
Thank
you.
No comments:
Post a Comment