0% found this document useful (0 votes)
5 views

C#_Collection_Generic_GenericCollection-Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C#_Collection_Generic_GenericCollection-Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Limitations in Array

Disadvantages of using arrays in C#:

 The array size is fixed.

 So, we should know in advance how many elements are going to be stored in the array.

 Once the array is created, then we can never increase the size of an array.

 If you want then we can do it manually by creating a new array and copying the old array
elements into the new array.

 As the array size is fixed, if we allocate more memory than the requirement then the extra
memory will be wasted.

 On the other hand, if we allocate less memory than the requirement, then it will create the
problem.

 As the elements of an array are stored in contiguous memory locations.

 So insertions and deletions of array elements are very difficult and also time-consuming.

 So the time complexity increase in insertion and deletion operation.

 We can never insert an element into the middle of an array.

 It is also not possible to delete or remove elements from the middle of an array.

 To overcome the above problems Array Class and Collections are introduced in C#.

Collection

Collection is a data structure which allows to store the element in a specialized way.

C# collection types are designed to store, manage and manipulate similar data more efficiently. Data
manipulation includes adding, removing, finding, and inserting data in the collection. Collection types
implement the following common functionality:

 Adding and inserting items to a collection

 Removing items from a collection

 Finding, sorting, searching items

 Replacing items
 Copy and clone collections and items

 Capacity and Count properties to find the capacity of the collection and number of items in the
collection

.NET supports two types of collections, generic collections and non-generic collections. Prior to .NET 2.0,
it was just collections and when generics were added to .NET, generics collections were added as well.

Generic collections with work generic data type. Learn more about generics here: Generics in C#.

The following table lists and matches these classes.

Non-generic Generic

ArrayList -------------> List

HashTable -------------> Dictionary

SortedList -------------> SortedList

Stack -------------> Stack

Queue -------------> Queue

1. Non-Generic

In non-generic collections, each element can represent a value of a different type. The collection size is
not fixed. Items from the collection can be added or removed at runtime.

Collection classes are available under System.Collection.

Different types of collections are

 ArrayList
 Hashtable
 Sortedlist
 Stack
 Queue
9999

1 ArrayList

It represents ordered collection of an object that can be indexed individually.

It is basically an alternative to an array. However, unlike array you can add and remove items from a list
at a specified position using an

index and the array resizes itself automatically. It also allows dynamic memory allocation, adding,
searching and sorting items in the list.

public virtual int Add(object value);


public virtual void AddRange(ICollection c);
public virtual void Clear();
public virtual bool Contains(object item);
public virtual int IndexOf(object);
public virtual int RemoveAt(int);
public virtual int Remove();
public virtual int RemoveRange();
virtual virtual int Sort();
virtual int Reverse();
public virtual void Insert();
public virtual int InsertRange();
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace BasicCSharpConcept
{
class CollectionsDemo
{

public void ArrayListDemo()


{
Student student1 = new Student();
student1.RollNo = "101";
student1.Name = "John";
student1.Age = 20;

Student student2 = new Student()


{
RollNo = "102",
Name = "Samual",
Age = 19,
};
Student student3 = new Student { Age = 25, Name = "David", RollNo = "103" };
ArrayList list = new ArrayList();
list.Add("String1");
list.Add('C');
list.Add(45.75f);
list.Add(student1);
list.Add(student2);
list.Add(student3);
list.Add(45);
list.Add(78);
list.Add(33);
list.Add(56);
list.Add(12);
list.Add(23);
list.Add(9);

foreach (var l in list)


{
Console.WriteLine(l);
}
ArrayList list1 = new ArrayList();

list1.Add(59);
list1.Add(57);
list1.Add(55);
list1.Add(53);
list1.Add(51);
// Console.ReadLine();
Console.WriteLine("Elements After Adding New List to Array List");
list.AddRange(list1);

foreach (var l in list)


{
Console.WriteLine(l);
}

Console.ReadLine();
if (list.Contains("String2"))
{
Console.WriteLine("Elements is Available at Index No {0}", list.IndexOf("String1"));
}
else
{
Console.WriteLine("Elements is Not Available in the List");
}

int index= list.IndexOf(student1);


int lastindex1 = list.IndexOf(student3);

Console.WriteLine("Index No of Student1 and Student3 is {0} and {1}", index, lastindex1);

list.RemoveRange(index, 3);
Console.WriteLine("Elements Removing Adding list1 to Array List");
//list.RemoveRange(list1);
foreach (var l in list)
{
Console.WriteLine(l);
}
list.Remove("String1");
Console.WriteLine("Elements Removing String1 from Array List");
//list.RemoveRange(list1);
foreach (var l in list)
{
Console.WriteLine(l);
}
list.RemoveAt(1);
list.Remove('C');
Console.ReadLine();
Console.WriteLine("Elements Removing Element at 1 Index from Array List");
//list.RemoveRange(list1);
Console.WriteLine("before Sorting Elements");
foreach (var l in list)
{
Console.WriteLine(l);
}

Console.WriteLine("After Sorting Elements in Ascending order from Array List");


list.Sort();
foreach (var l in list)
{
Console.WriteLine(l);
}
Console.WriteLine("After Sorting Elements in decending order from Array List");
list.Reverse();
foreach (var l in list)
{
Console.WriteLine(l);
}

int count=list.Count;
Console.WriteLine("Number of Elements are {0} Before Clearing All Elements",count);
list.Clear();
int count1 = list.Count;
Console.WriteLine("Number of Elements are {0} After Clearing All Elements", count1);
list.Insert(0, 100);
list.Insert(1, 200);
Console.WriteLine("Number of Elements are {0} After Inserting", count);
foreach (var l in list)
{
Console.WriteLine(l);
}
list.InsertRange(1,list1);
Console.WriteLine(" After Inserting the Range");
foreach (var l in list)
{
Console.WriteLine(l);
}
}
}
}

2 Hashtable

It uses a key to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a useful key
value. Each item in the hash table has a key/value pair. The key is used to access the items in the
collection.

public virtual void Add(object key, object value);


public virtual bool ContainsKey(object key);
public virtual bool ContainsValue(object value);
public virtual void Remove(object key);

ht.Add("001", "Zara Ali");


ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");

// Get a collection of the keys.


ICollection key = ht.Keys;

foreach (string k in key) {


Console.WriteLine(k + ": " + ht[k]);
}
public void HashTableDemo()
{
Hashtable ht = new Hashtable();
ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");

ICollection key = ht.Keys;


//foreach (string k in key)
//{
// Console.WriteLine(k + ": " + ht[k]);
//}
Console.WriteLine("Only Keys");
//foreach (string k in key)
//{
// Console.WriteLine( ": " +k);
//}

//ICollection value = ht.Values;

//Console.WriteLine("Only Values");
//foreach (string v in value)
//{
// Console.WriteLine(": " + v);
//}

//bool k = ht.ContainsKey("008");
//if (k == true)
//{
// Console.WriteLine("Key is available in the list with value {0} ", ht["007"]);
// }
//else
//{
// Console.WriteLine("Key is not available in the list");
//}
//string v3= "Mausam Benazir Nur";
//bool v1 = ht.ContainsValue("Mausam Benazir Nur");

//if (v1 == true)


//{
// Console.WriteLine("Value is available in the list with Key ");
//}
//else
//{
// Console.WriteLine("Key is not available iConsole.WriteLine("Key is not available in the list");
//}

foreach (string k in key)


{
Console.WriteLine(k + ": " + ht[k]);
}

ht.Remove("007");
Console.WriteLine("After Removing 007 from List");

foreach (string k in key)


{
Console.WriteLine(k + ": " + ht[k]);
}

3 SortedList

It uses a key as well as an index to access the items in a list.

int indexkey= sl.IndexOfKey("007");


int indexvalue = sl.IndexOfValue("Mausam Benazir Nur");
sl.Add("001", "Zara Ali");
sl.Add("002", "Abida Rehman");
sl.Add("003", "Joe Holzner");
sl.Add("004", "Mausam Benazir Nur");
sl.Add("005", "M. Amlan");
sl.Add("006", "M. Arif");
sl.Add("007", "Ritesh Saikia");

// get a collection of the keys.


ICollection key = sl.Keys;

foreach (string k in key) {


Console.WriteLine(k + ": " + sl[k]);
}
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed
using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using
a key , it is a Hashtable. The collection of items is always sorted by the key value.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CollectionDemo
{
public class SortedListDemo
{
public void SortedListDemo1()
{
SortedList sortedList = new SortedList();

sortedList.Add(600, "Suresh");
sortedList.Add(200, "Anil");

sortedList.Add(400, "Vinit");
sortedList.Add(500, "Rajesh");
sortedList.Add(100, "Sunil");
sortedList.Add(300, "Punit");

ICollection key = sortedList.Keys;


foreach (var k in key)
{
Console.WriteLine("Key is " + k);
}

ICollection value = sortedList.Values;


foreach (var v in value)
{
Console.WriteLine("value is " + v);
}
foreach (var k in key)
{
Console.WriteLine("For the Key {0} Value is {1} ", k, sortedList[k]);
}
Console.WriteLine("\n\n\n");
Console.WriteLine("Elements Through Index Number");

for (int i = 0; i < sortedList.Count; i++) {

Console.WriteLine(sortedList.GetByIndex(i));
}

Console.WriteLine("\n\n\n");
Console.WriteLine("Elements Through Key Number");

for (int i = 0; i < sortedList.Count; i++)


{

Console.WriteLine(sortedList.GetKey(i));
}
}
}
}

4 Stack

It represents a last-in, first out collection of object.

1 public virtual void Clear();

Removes all elements from the Stack.

2 public virtual bool Contains(object obj);

Determines whether an element is in the Stack.

3 public virtual object Peek();

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

4 public virtual object Pop();


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

5 public virtual void Push(object obj);

Inserts an object at the top of the Stack.

class Program {
static void Main(string[] args) {
Stack st = new Stack();

st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');

Console.WriteLine("Current stack: ");


foreach (char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();

st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");

foreach (char c in st) {


Console.Write(c + " ");
}

Console.WriteLine();

Console.WriteLine("Removing values ");


st.Pop();
st.Pop();
st.Pop();

Console.WriteLine("Current stack: ");


foreach (char c in st) {
Console.Write(c + " ");
}
}
}
It is used when you need a last-in, first-out access of items.

When you add an item in the list, it is called pushing the item and when you remove it, it is called
popping the item.

5 Queue

It represents a first-in, first out collection of object.

It is used when you need a first-in, first-out access of items. When you add an item in the list, it is call
1) public virtual void Clear();

Removes all elements from the Queue.

2 public virtual bool Contains(object obj);

Determines whether an element is in the Queue.

3 public virtual object Dequeue();

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

4 public virtual void Enqueue(object obj);

Adds an object to the end of the Queue.

using System;
using System.Collections;

namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
Queue q = new Queue();

q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');

Console.WriteLine("Current queue: ");


foreach (char c in q) Console.Write(c + " ");

Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q) Console.Write(c + " ");

Console.WriteLine();
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();//Unboxing
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();F
Console.WriteLine("The removed value: {0}", ch);

Console.ReadKey();
}
}
}
Boxing : Process of converting value type Eg Char or int type to the reference types is know as boxing
int i=10;
object o=i;//boxing it is done automatically no casting is required

UnBoxing : process of Converting reference type Eg Stack or Queue to Value type i.e int or char is know
unboxing
object o=10;
int i=(int)o;//unboxing it has to be casting by using cast operator “()”;

You might also like