SlideShare ist ein Scribd-Unternehmen logo
1 von 33
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
String in java
String in javaString in java
String in java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
C# String
C# StringC# String
C# String
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
interface in c#
interface in c#interface in c#
interface in c#
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 

Ähnlich wie Collections and its types in C# (with examples)

Collections generic
Collections genericCollections generic
Collections genericsandhish
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfarpitaeron555
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; CollectionArya
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; CollectionArya
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)Janki Shah
 

Ähnlich wie Collections and its types in C# (with examples) (20)

Collections generic
Collections genericCollections generic
Collections generic
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Collection Framework-1.pptx
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; Collection
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; Collection
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Chapter11
Chapter11Chapter11
Chapter11
 

Kürzlich hochgeladen

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Kürzlich hochgeladen (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Collections and its types in C# (with examples)

  • 2.  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.
  • 3.  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.
  • 4. 1. Generic collections 2. Non-Generic collections 3. Specialized collections
  • 5.  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.
  • 6.
  • 7.
  • 8.  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.
  • 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 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.
  • 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 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.
  • 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 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.
  • 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. NON-GENERIC CLASSES OR COLLECTIONS
  • 17.  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.
  • 18.  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.
  • 19.  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.
  • 20.  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.
  • 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(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();
  • 23.  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.
  • 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 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 ).
  • 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 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.
  • 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 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.
  • 32.  Array-List can resize dynamically during runtime.