By: Aijaz Ali Abro
 A collection is a set of similarly typed objects that
are grouped together.
 The principal benefit of collections is that they
standardize the way groups of objects are
handled by your programs.
 Collections are data structures that holds data in
different ways for flexible operations . C#
Collection classes are defined as part of the
System. Collections or System.Collections.Generic
namespace.
 Most collection classes implement the same
interfaces, and these interfaces may be
inherited to create new collection classes that
fit more specialized data storage needs.
1. Generic collections
2. Non-Generic collections
3. Specialized collections
 The System.Collections.Generic namespace
contains interfaces and classes that define
generic collections, which allow users to
create strongly typed collections that provide
better type safety and performance than non-
generic strongly typed collections.
 Fast lookups are critical. The Dictionary type
provides fast lookups with keys to get values.
With it we use keys and values of any type,
including ints and strings.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary. Add("cat", 2);
dictionary. Add("dog", 1);
dictionary. Add("llama", 0);
foreach (KeyValuePair<string, int> pair in dictionary)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
OUTPUT:
cat 2
dog 1
llama 0
 Arrays do not dynamically resize.
The List type does. With List, you do not need
to manage the size on your own. This type is
ideal for linear collections not accessed by
keys. It provides many methods and
properties.
List<int> list = new List<int>();
list. Add(2);
list. Add(3);
list. Add(5);
list. Add(7);
foreach (int prime in list)
{
Console.WriteLine(prime);
}
OUTPUT:
2
3
5
7
 Queue is a FIFO collection. It processes
elements in a first-in, first-out order. To
restate, it handles the elements that it
received longest ago first.
 Queue is a generic type with one type
parameter.
Queue<string> numbers = new Queue<string>();
numbers.Enqueue("one");
numbers.Enqueue("two");
numbers.Enqueue("three");
foreach(string number in numbers )
{
Console.WriteLine(number);
}
OUTPUT:
one
two
three
 The Stack class represents a last-in-first-out
(LIFO) Stack of Objects. Stack follows the
push-pop operations. That is we can Push
(insert) Items into Stack and Pop (retrieve) it
back . Stack is implemented as a circular
buffer. It follows the Last In First Out (LIFO)
system. That is we can push the items into a
stack and get it in reverse order. Stack
returns the last item first. As elements are
added to a Stack, the capacity is automatically
increased as required through reallocation.
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(1000);
stack.Push(10000);
foreach (int i in stack)
{
Console.WriteLine(i);
}
OUTPUT:
10000
1000
100
NON-GENERIC CLASSES OR COLLECTIONS
 The non-generic collections have been part of the .NET
Framework since version 1.0. They are defined in
theSystem.Collections namespace. The non-generic collections
are general purpose data structures that operate
on object references. Thus, they can manage any type of object,
but not in a type-safe manner. This is both their advantage and
disadvantage. Because they operate on object references, you
can mix various types of data within the same collection. This
makes them useful in situations in which you need to manage a
collection of different types of objects or when the type of
objects being stored are not known in advance. However, if you
intend a collection to store a specific type of object, then the
non-generic collections do not have the type-safety that is found
in the generic collections.
 The non-generic collections are defined by a set of interfaces
and the classes that implement those interfaces.
 System. Collections namespace define the
following non-generic collection classes.
Class Description
ArrayList A dynamic array. This is
an array that can grow as
needed.
Hashtable A hash table for
key/value pairs.
Queue A first-in, first-out list.
SortedList A sorted list of key/value
pairs.
Stack A first-in, last-out list.
 The ArrayList class supports dynamic arrays,
which can grow or shrink as needed.
 An ArrayList is a variable-length array of
object references that can dynamically
increase or decrease in size.
 An ArrayList is created with an initial size.
When this size is exceeded, the collection is
automatically enlarged. When objects are
removed, the array can be shrunk.
 using an arrayList and very easily we can add,
insert , delete , Sort , view etc.
 It is very flexible because we can add without
any size information , that is it will grow
dynamically and also shrink.
 Adding data / objects into ArrayList:
ArrayList alist = new ArrayList();
alist.Add(“Aijaz Ali”);
alist.Add(1345);
alist.Add(1345.87);
alist.Add(true);
alist.Add(‘G’);
Continue…
 Syntax :
foreach(dataType var in ArrayListRef)
{
Console.WriteLine(var);
}
 dataType // int , char , string , bool etc.
 var // int a , string name , bool b.
 In // keyword.
 ArrayListRef // ArrayList list = new ArrayList();
 Hashtable in C# represents a collection of
key/value pairs which maps keys to value.
Any non-null object can be used as a key but
a value can. We can retrieve items from
hashTable to provide the key . Both keys and
values are Objects.
 Adding data / objects into HashTable :
 Hashtable weeks = new Hashtable();
weeks.Add("1", "Sunday");
weeks.Add("2", "Monday");
weeks.Add("3", "Tuesday");
weeks.Add("4", "Wed Day");
weeks.Add("5", "Thruway");
weeks.Add("6", "Friday");
weeks.Add("7", "Sat Day");
 The Queue works like FIFO system , a first-in,
first-out collection of Objects. Objects stored
in a Queue are inserted at one end and
removed from the other. The Queue provide
additional insertion, extraction, and
inspection operations. We can Enqueue (add)
items in Queue and we can Dequeue(remove
from Queue ).
 Adding data / objects using Queue class :
 Queue days = new Queue();
days.Enqueue("Sunday");
days.Enqueue("Monday");
days.Enqueue("Tuesday");
days.Enqueue("Wednesday");
//Remove first object value “Sunday”.
days.Dequeue();
 Foreach (string _names in days)
{
Console.WriteLine(_names);
}
OUTPUT:
Monday
Tuesday
Wednesday
 The Stack class represents a last-in-first-out
(LIFO) Stack of Objects. Stack follows the
push-pop operations. That is we can Push
(insert) Items into Stack and Pop (retrieve) it
back . Stack is implemented as a circular
buffer. It follows the Last In First Out (LIFO)
system. That is we can push the items into a
stack and get it in reverse order. Stack
returns the last item first. As elements are
added to a Stack, the capacity is automatically
increased as required through reallocation.
 Adding data / objects into Stack :
 Stack stack = new Stack();
stack.Push("Sunday");
stack.Push("Monday");
stack.Push(12345);
stack.Push(1123.56);
 Console.WriteLine(stack.Pop());
OUTPUT:
1123.56
 Non-Generic collections - These are the collections that
can hold elements of different data types. It holds all
elements as object type. So it includes overhead of type
conversions ( overhead of implicit and explicit
conversions). These are also called weakly typed.
 Generic collections - These are the collections that can
hold data of same type and we can decide what type of
data that collections can hold. These are also called
strongly typed.
 Some advantages of generic collections - Type Safe,
Secure, reduced overhead of type conversions.
 Arrays are strongly typed.
 Array-Lists are not strongly typed.
 Elements in Arrays have to be of same data
type (int, string, double, char, bool…).
 Elements in Array-List can have any type of
data. Note: If Array-List has combined data
types then type cast is must.
 Arrays are fixed specified length size
therefore they cannot be resize dynamically
during runtime.
 Array-List can resize dynamically during
runtime.
THE END

Collections and its types in C# (with examples)

  • 1.
  • 2.
     A collectionis a set of similarly typed objects that are grouped together.  The principal benefit of collections is that they standardize the way groups of objects are handled by your programs.  Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System. Collections or System.Collections.Generic namespace.
  • 3.
     Most collectionclasses implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
  • 4.
    1. Generic collections 2.Non-Generic collections 3. Specialized collections
  • 5.
     The System.Collections.Genericnamespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non- generic strongly typed collections.
  • 8.
     Fast lookupsare critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings.
  • 9.
    Dictionary<string, int> dictionary= new Dictionary<string, int>(); dictionary. Add("cat", 2); dictionary. Add("dog", 1); dictionary. Add("llama", 0); foreach (KeyValuePair<string, int> pair in dictionary) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } OUTPUT: cat 2 dog 1 llama 0
  • 10.
     Arrays donot dynamically resize. The List type does. With List, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. It provides many methods and properties.
  • 11.
    List<int> list =new List<int>(); list. Add(2); list. Add(3); list. Add(5); list. Add(7); foreach (int prime in list) { Console.WriteLine(prime); } OUTPUT: 2 3 5 7
  • 12.
     Queue isa FIFO collection. It processes elements in a first-in, first-out order. To restate, it handles the elements that it received longest ago first.  Queue is a generic type with one type parameter.
  • 13.
    Queue<string> numbers =new Queue<string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); foreach(string number in numbers ) { Console.WriteLine(number); } OUTPUT: one two three
  • 14.
     The Stackclass represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push (insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
  • 15.
    Stack<int> stack =new Stack<int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); foreach (int i in stack) { Console.WriteLine(i); } OUTPUT: 10000 1000 100
  • 16.
  • 17.
     The non-genericcollections have been part of the .NET Framework since version 1.0. They are defined in theSystem.Collections namespace. The non-generic collections are general purpose data structures that operate on object references. Thus, they can manage any type of object, but not in a type-safe manner. This is both their advantage and disadvantage. Because they operate on object references, you can mix various types of data within the same collection. This makes them useful in situations in which you need to manage a collection of different types of objects or when the type of objects being stored are not known in advance. However, if you intend a collection to store a specific type of object, then the non-generic collections do not have the type-safety that is found in the generic collections.  The non-generic collections are defined by a set of interfaces and the classes that implement those interfaces.
  • 18.
     System. Collectionsnamespace define the following non-generic collection classes. Class Description ArrayList A dynamic array. This is an array that can grow as needed. Hashtable A hash table for key/value pairs. Queue A first-in, first-out list. SortedList A sorted list of key/value pairs. Stack A first-in, last-out list.
  • 19.
     The ArrayListclass supports dynamic arrays, which can grow or shrink as needed.  An ArrayList is a variable-length array of object references that can dynamically increase or decrease in size.  An ArrayList is created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk.
  • 20.
     using anarrayList and very easily we can add, insert , delete , Sort , view etc.  It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink.
  • 21.
     Adding data/ objects into ArrayList: ArrayList alist = new ArrayList(); alist.Add(“Aijaz Ali”); alist.Add(1345); alist.Add(1345.87); alist.Add(true); alist.Add(‘G’); Continue…
  • 22.
     Syntax : foreach(dataTypevar in ArrayListRef) { Console.WriteLine(var); }  dataType // int , char , string , bool etc.  var // int a , string name , bool b.  In // keyword.  ArrayListRef // ArrayList list = new ArrayList();
  • 23.
     Hashtable inC# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key . Both keys and values are Objects.
  • 24.
     Adding data/ objects into HashTable :  Hashtable weeks = new Hashtable(); weeks.Add("1", "Sunday"); weeks.Add("2", "Monday"); weeks.Add("3", "Tuesday"); weeks.Add("4", "Wed Day"); weeks.Add("5", "Thruway"); weeks.Add("6", "Friday"); weeks.Add("7", "Sat Day");
  • 25.
     The Queueworks like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue(remove from Queue ).
  • 26.
     Adding data/ objects using Queue class :  Queue days = new Queue(); days.Enqueue("Sunday"); days.Enqueue("Monday"); days.Enqueue("Tuesday"); days.Enqueue("Wednesday"); //Remove first object value “Sunday”. days.Dequeue();
  • 27.
     Foreach (string_names in days) { Console.WriteLine(_names); } OUTPUT: Monday Tuesday Wednesday
  • 28.
     The Stackclass represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push (insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
  • 29.
     Adding data/ objects into Stack :  Stack stack = new Stack(); stack.Push("Sunday"); stack.Push("Monday"); stack.Push(12345); stack.Push(1123.56);  Console.WriteLine(stack.Pop()); OUTPUT: 1123.56
  • 30.
     Non-Generic collections- These are the collections that can hold elements of different data types. It holds all elements as object type. So it includes overhead of type conversions ( overhead of implicit and explicit conversions). These are also called weakly typed.  Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold. These are also called strongly typed.  Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.
  • 31.
     Arrays arestrongly typed.  Array-Lists are not strongly typed.  Elements in Arrays have to be of same data type (int, string, double, char, bool…).  Elements in Array-List can have any type of data. Note: If Array-List has combined data types then type cast is must.  Arrays are fixed specified length size therefore they cannot be resize dynamically during runtime.
  • 32.
     Array-List canresize dynamically during runtime.
  • 33.